使用group by计算Distinct字段

时间:2017-11-03 09:56:35

标签: mysql

我在这里尝试做

SELECT b.sponso , b.source_id , Count(Distinct b.source_id) As nb_part
FROM buzzes b 
WHERE b.type = 3 AND b.sponso_id != 0
GROUP BY b.source_id , b.sponso 

输出:

+------------+--------------+--------+
| Sponso     | source_id   | nb_part | 
+------------+--------------+--------+
| A          | 954711      | 1       | 
| A          | 587741      | 1       | 
| B          | 321447      | 1       | 
| B          | 350         | 1       |
+------------+--------------+--------+

我期待的是

+------------+--------------+--------+
| Sponso     | source_id   | nb_part | 
+------------+--------------+--------+
| A          | 954711      | 2       | 
| B          | 321447      | 2       | 
+------------+--------------+--------+

我想通过Sponso计算nb_part和group的总和,但我仍然坚持我的查询

1 个答案:

答案 0 :(得分:1)

您似乎想要source_id的最大值和每source_id的不同sponso的数量。 " Per sponso"转换为SQL中的GROUP BY sponso

SELECT sponso, MAX(source_id) AS source_id, COUNT(DISTINCT source_id) AS nb_part
FROM buzzes
WHERE type = 3 AND sponso_id != 0
GROUP BY sponso
ORDER BY sponso;

或者您可能希望聚合查询:

SELECT sponso, MAX(source_id) AS source_id, SUM(nb_part) AS nb_part
FROM
(
  SELECT b.sponso , b.source_id , Count(Distinct b.source_id) As nb_part
  FROM buzzes b 
  WHERE b.type = 3 AND b.sponso_id != 0
  GROUP BY b.source_id , b.sponso 
)
GROUP BY sponso
ORDER BY sponso;