有下列表
create table test(RiQi datetime,ShuLiang int,JieGuo nvarchar(50))
insert test values('2013-2-1',10,'成功')
insert test values('2013-2-2',20,'失败')
insert test values('2013-2-3',10,'失败')
insert test values('2013-2-4',40,'成功')
insert test values('2013-2-5',20,'失败')
insert test values('2013-2-6',30,'成功')
insert test values('2013-2-7',30,'成功')
(1)如何用sql语句生成下列结果?
ShuLiang 成功 失败
——————————
10 1 1
20 0 2
30 2 0
40 1 0
(2)用sql语句,查询表中所有数据,在查询结果中,把第X天的数量设置为第X-1天与第X-2天的数量之和(若x-1或x-2在表中不存在,x-1或x-2的数量为0)
结果如下:
RIQI ShuLiang
——————————
2013-02-01 0
2013-02-02 10
2013-02-03 30
2013-02-04 30
2013-02-05 50
2013-02-06 60
2013-02-07 50
------解决方案--------------------
第一个用count(case when...)就行
------解决方案--------------------
select ShuLiang
,count(case when JieGuo='成功' then 1 end) [成功]
,count(case when JieGuo='失败' then 1 end) [失败]
from test with(nolock)
group by ShuLiang
--结果
ShuLiang 成功 失败
----------- ----------- -----------
10 1 1
20 0 2
30 2 0
40 1 0
------解决方案--------------------
第1、
select ShuLiang,
成功=SUM(case when JieGuo='成功' then 1 else 0 end),
失败=SUM(case when JieGuo='失败' then 1 else 0 end)
from test
group by ShuLiang
第2没看明白
------解决方案--------------------
create table test(RiQi datetime,ShuLiang int,JieGuo nvarchar(50))
insert test values('2013-2-1',10,'成功')
insert test values('2013-2-2',20,'失败')
insert test values('2013-2-3',10,'失败')
insert test values('2013-2-4',40,'成功')
insert test values('2013-2-5',20,'失败')
insert test values('2013-2-6',30,'成功')
insert test values('2013-2-7',30,'成功')
select
ShuLiang,
成功=sum(case when JieGuo='成功' then 1 else 0 end),
失败=sum(case when JieGuo='失败' then 1 else 0 end)
from
test
group by
ShuLiang
/*
ShuLiang 成功 失败
-------------------------------
10 1 1
20 0 2
30 2 0
40 1 0
*/
select
RiQi,