这是原始数据:
这是SQL:
select c.newsId,SUM(c.amount) as amount,SUM(c.[1]) as '1',SUM(c.[2]) as '2',SUM(c.[3]) as '3',SUM(c.[4]) as '4',SUM(c.[5]) as '5' from (select b.newsId,SUM(a) as amount, SUM(case b.star when 1 then a else 0 end) '1', SUM(case b.star when 2 then a else 0 end) '2', SUM(case b.star when 3 then a else 0 end) '3', SUM(case b.star when 4 then a else 0 end) '4', SUM(case b.star when 5 then a else 0 end) '5' from (select newsId,star,COUNT(1) as a from test group by star,newsId) b group by b.newsId,b.star) c group by c.newsId
这是处理结果:
给分楼主 :)
给分,,我就喜欢这样的回复结果。
如果你只是这个三星的问题的话,有个方法
select count(*) as Star3Count where 星级=3
UNION ALL
select count(*0 as Star4Count where 星级=4
...
这个最好不要用sql处理,用C#处理,Dictionary<int,int>存储,前面int类型的key就存储1,2,3,4,5,代表几星。后面int类型的value 存储每个星的个数。sql语句把这个表的记录查询出来,在C#用for循环一次就可以了。
我之前的做法是定义一个表变量 插入状态值.到时候group by 出来的数据left join 一下
1、先根据星级group by;
2、将结果使用pivot翻转;
3、计算总数与翻转结果连接。