我需要获得与每个用户的国家/地区计数和汇率相关的唯一计数
我已经为数据库提出了这个基本设计,其中uid
是用户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);
这是我用于获取每日计数的查询
$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>';
};
我收到了这个结果
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
预期结果
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
我想我需要类似SELECT DISTINCT country FROM stats
的内容来获取主要查询中的国家/地区计数。
请参阅并建议任何可行的方法。
由于
答案 0 :(得分:2)
您可以使用子查询来实现此目的:
export M2_HOME=/usr/local/apache-maven/apache-maven-3.3.9
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
mvn --version
也可在sqlfiddle处找到。
答案 1 :(得分:1)
SUM需要一个列,并在其中包含字符串'rate'
,从费率列名称中删除'
试试这个,
SELECT
COUNT(DISTINCT `ip`)AS `count`,
`country`,
SUM(rate) AS `sum`
FROM `stats`
GROUP BY `uid`, `date`
答案 2 :(得分:1)
您还必须将country
添加到GROUP条件中:
SELECT
COUNT(DISTINCT `ip`) AS `count`,
`country`,
COUNT(`country`) as `countryViewsByUser`, -- added
SUM(`rate`)AS `sum`
FROM
`stats`
GROUP BY
`uid`,
`date`,
`country` -- added
答案 3 :(得分:0)
您只需将国家/地区添加到您的群组中,如下所示
$query="
SELECT
COUNT(DISTINCT `ip`)AS `count`,
`country`,
COUNT(DISTINCT `country`) AS country_count,
SUM(`rate`) AS `sum`
FROM `stats`
GROUP BY `country`, `uid`, `date`
";
请你远离mysqli_ *函数,然后看看PDO而不是