dtio35880438 2016-08-24 23:07
浏览 90
已采纳

Mysql从stats数据库中获取多个计数

I need to get unique counts along with country counts and sum rate for every user

I have come up with this basic design for database where uid is user id

DROP TABLE IF EXISTS `stats`;
CREATE TABLE IF NOT EXISTS `stats` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `uid` int(5) UNSIGNED NOT NULL,
  `country` int(3) UNSIGNED NOT NULL,
  `ip` int(10) UNSIGNED NOT NULL,
  `date` int(10) UNSIGNED NOT NULL,
  `timestamp` int(10) UNSIGNED NOT NULL,
  `rate` int(10) UNSIGNED NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `stats` 
(`id`, `uid`, `country`, `ip`, `date`, `timestamp`, `rate`) VALUES
(1, 1, 10, 1111111111, 2222222222, 3333333333, 100),
(2, 1, 10, 1111111112, 2222222222, 3333333333, 100),
(3, 2, 10, 1111111111, 2222222222, 3333333333, 100),
(4, 1, 10, 1111111114, 2222222223, 3333333333, 100),
(5, 1, 11, 1111111112, 2222222223, 3333333333, 100),
(6, 1, 10, 1111111111, 2222222223, 3333333333, 100);

And this is the query I am using to fetch daily counts

$query="
SELECT `uid`,
COUNT(DISTINCT `ip`)AS `count`, 
`country`, 
SUM(`rate`) AS `sum`,
`date`
FROM `stats` 
GROUP BY `uid`, `date`
";
$result=mysqli_query($connection, $query) or trigger_error(mysqli_error($connection), E_USER_ERROR);
while($row = mysqli_fetch_assoc($result)){
echo 'userid:'.$row['uid'].' count:'.$row['count'].' country:'.$row['country'].' sum:'.$row['sum'].' date:'.$row['date'].'<br>';
};

I am getting this result

userid:1 count:2 country:10 sum:200 date:2222222222
userid:1 count:3 country:10 sum:300 date:2222222223
userid:2 count:1 country:10 sum:100 date:2222222222

Expected result

userid:1 count:2 country:10=>2        sum:200 date:2222222222
userid:1 count:3 country:10=>2, 11=>1 sum:300 date:2222222223
userid:2 count:1 country:10=>1        sum:100 date:2222222222

I guess I need something like SELECT DISTINCT country FROM stats to get country counts in main query.

Please see and suggest any possible way to do this.

Thanks

展开全部

  • 写回答

4条回答 默认 最新

  • douju3911 2016-08-24 23:42
    关注

    You can use subquery to achieve this:

    SELECT
      t.uid,
      SUM(t.count) AS count,
      GROUP_CONCAT(CONCAT(t.country, ' => ', t.views) SEPARATOR ', ') AS country,
      SUM(t.sum) as sum,
      t.date
    FROM (
      SELECT
        s.uid,
        COUNT(DISTINCT s.ip) AS count,
        s.country,
        COUNT(s.country) as views,
        SUM(s.rate)AS sum,
        s.date
      FROM stats s
      GROUP BY uid, date, country
      ) AS t
    GROUP BY
    t.uid,
    t.date
    

    Also available at sqlfiddle.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部