我正在尝试为此报表编写SQL查询,以按日期分组并获取所有唯一值的计数。我的问题是我不知道我会提前拥有多少个唯一值。
样品表:
+--------+--------+
| Date | Name |
+--------+--------+
| 1/1/18 | John |
| 1/1/18 | John |
| 1/1/18 | Sylvia |
| 1/2/18 | Sylvia |
+--------+--------+
这是我尝试过的方法,但它要求我知道表中存在John和Sylvia。如果有50,000个唯一名称而不必键入所有CASE语句,那么解决方法是什么。
SELECT
date,
SUM(CASE WHEN name='John' THEN 1 ELSE 0 END) AS John,
SUM(CASE WHEN name='Sylvia' THEN 1 ELSE 0 END) AS Sylvia
FROM myTable
GROUP BY date;
预期输出:
+--------+------+--------+-----+
| Date | John | Sylvia | ... |
+--------+------+--------+-----+
| 1/1/18 | 2 | 1 | ... |
| 1/2/18 | 0 | 1 | ... |
+--------+------+--------+-----+
答案 0 :(得分:0)
一个简单的
SELECT date, name, count(*) FROM myTable GROUP BY date, name;
应该工作
答案 1 :(得分:0)
您可以使用Dynamic PIVOT.
Declare @sql nvarchar(max)
set @sql = 'select *
from (select *,count(name)cnt from #mytable group by name,date)A
PIVOT
( sum(cnt)
FOR name
in ( '+stuff(( select distinct ', '+ name from #mytable group by name for xml path('')),1,1,'')+')
)as PIVOTTABLE'
EXECUTE sp_executesql @sql;
此链接可以帮助您MySQL Select Query to generate dynamic column Result