例如csv中的数据是
#row, col, number
y1,x1,1
y2,x2,1
y2,x2,1
y2,x3,1
如果我使用简单的组SQL,它可以显示为一维
select y1,x1,count(*) from data group by 1,2 order by 1,2
1-D结果是
row col count(*)
y1 x1 1
y2 x2 2
y2 x3 3
我想表现出像
row x1 x2 x3
y1 1 0 0
y2 0 2 1
如果col仅限于&x;' x2' x3' x3',则可以使用一个SQL显示为2-D ?
答案 0 :(得分:2)
SELECT row,
SUM(CASE WHEN col= 'x1' THEN 1 else 0 END) AS x1,
SUM(CASE WHEN col= 'x2' THEN 1 else 0 END) AS x2,
SUM(CASE WHEN col= 'x3' THEN 1 else 0 END) AS x3
FROM data
GROUP BY row;
答案 1 :(得分:1)
试试这个
select row,isnull(sum(x2),0) as X2,isnull(sum(x3),0) as X3
from(select row,case when col = 'x1'
then
cnt
end as x1,
case when col = 'x2'
then
cnt
end as x2,
case when col = 'x3'
then
cnt
end as x3
from
(select row,col,count(*) as cnt from test1 group by row,col ) as test)
as total
group by row