统计sql怎么写
表table
怎么实现下面统计 将很好和较好合并统计,很差和较差合并统计
VoteValueStr ct
否 3
好 8
--这里是很好+较好
一般 2
差 2
--这里是很差+较差 ------解决方案--------------------select (case when right(votevaluestr,1) in('好','差') then right(votevaluestr,1) else votevaluestr end)as votevaluestr,sum(ct)
from tb
group by (case when right(votevaluestr,1) in('好','差') then right(votevaluestr,1) else votevaluestr end)
------解决方案--------------------create table tb(votevaluestr nvarchar(10),ct int)
insert into tb select '否',3
insert into tb select '很差',1
insert into tb select '很好',1
insert into tb select '较差',1
insert into tb select '较好',7
insert into tb select '一般',2
go
select (case when right(votevaluestr,1) in('好','差') then right(votevaluestr,1) else votevaluestr end)as votevaluestr,sum(ct)ct
from tb
group by (case when right(votevaluestr,1) in('好','差') then right(votevaluestr,1) else votevaluestr end)
/*
votevaluestr ct
------------ -----------
差 2
否 3
好 8
一般 2
(4 行受影响)
*/
go
drop table tb
------解决方案--------------------select sum(ct) from table where VoteValueStr="较好" or VoteValueStr="很好"
select sum(ct) from table where VoteValueStr="较差" or VoteValueStr="很差"
------解决方案--------------------
--创建测试表
create table kb(votevaluestr nvarchar(10),ct int)
--插入数据
insert into kb
select N'否',3
union all
select N'很差',1
union all
select N'很好',1
union all
select N'较差',1
union all
select N'较好',7
union all
select N'一般',2
select vaotevaluestr,sum(ct) ct from (select case when votevaluestr like '%差%' then '差' when votevaluestr like '%好%' then '好' else votevaluestr end vaotevaluestr,ct from kb) b group by vaotevaluestr
差 2
否 3
好 8
一般 2
------解决方案--------------------结合case when和聚集函数来写
一楼的答案就很不错
------解决方案--------------------借用一下4楼的造数语句
----创建测试表
--create table kb(votevaluestr nvarchar(10),ct int)