我在这里尝试做
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的总和,但我仍然坚持我的查询
答案 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;