【问题标题】:Get data horizontal in SQL在 SQL 中水平获取数据
【发布时间】:2021-02-02 15:35:23
【问题描述】:
我有这个问题:
SELECT X, COUNT(*) AS TotalCount
FROM Table GROUP BY X, Y
ORDER BY X asc
它回来了:
X | Count
__________
A | 10
A | 11
A | 1
B | 2
B | 5
B | 6
我正在努力做到这一点,如果有人可以帮助我,谢谢
X | Count1 | Count2 | Count3
A | 10 | 11 | 1
B | 2 | 6 | 5
【问题讨论】:
标签:
sql
sql-server
count
pivot
aggregate-functions
【解决方案1】:
您通常会使用条件聚合来执行此操作。假设您想按y 订购列,您还可以使用窗口函数:
select x,
max(case when rn = 1 then totalcount end) count1,
max(case when rn = 2 then totalcount end) count2,
max(case when rn = 3 then totalcount end) count3
from (
select x, count(*) as totalcount,
row_number() over(partition by x order by y) rn
from mytable
group by x, y
) t
order by x
【解决方案2】:
您可以使用条件聚合进行透视:
select x,
sum(case when y = @val1 then 1 else 0 end),
sum(case when y = @val2 then 1 else 0 end),
sum(case when y = @val3 then 1 else 0 end)
from t
group by x;
不清楚每一列的具体值是什么。