如有表
ID 年份 状态 金额
1 2008 申请 110
2 2008 已批 220
3 2008 已退 330
4 2009 申请 440
5 2009 不批 550
--------------------------------要查询的结果为
年份 受理条数 受理金额 已退条数 已退金额
2008 3 660 1 330
2009 2 990 0 0受理 = 申请 + 已批 + 不批
已退 = 已退谢谢
ID 年份 状态 金额
1 2008 申请 110
2 2008 已批 220
3 2008 已退 330
4 2009 申请 440
5 2009 不批 550
--------------------------------要查询的结果为
年份 受理条数 受理金额 已退条数 已退金额
2008 3 660 1 330
2009 2 990 0 0受理 = 申请 + 已批 + 不批
已退 = 已退谢谢
年份,count(1) as 受理条数,sum(金额) as 受理金额,
sum(case 状态 when '已退' then 1 else 0 end) as 已退条数,
sum(case 状态 when '已退' then 金额 else 0 end) as 已退金额
from
tb
group by
年份
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([ID] int,[年份] int,[状态] varchar(4),[金额] int)
insert [tb]
select 1,2008,'申请',110 union all
select 2,2008,'已批',220 union all
select 3,2008,'已退',330 union all
select 4,2009,'申请',440 union all
select 5,2009,'不批',550
/*
年份 受理条数 受理金额 已退条数 已退金额
2008 3 660 1 330
2009 2 990 0 0受理 = 申请 + 已批 + 不批
已退 = 已退
*/
select 年份,
受理条数=sum(case when [状态]='申请' or [状态]='已批' or [状态]='不批' then 1 else 0 end),
受理金额=sum(case when [状态]='申请' or [状态]='已批' or [状态]='不批' then [金额] else 0 end),
已退条数=sum(case when [状态]='已退' then 1 else 0 end),
已退金额=sum(case when [状态]='已退' then 1 else 0 end)
from [tb]
group by 年份/*
年份 受理条数 受理金额 已退条数 已退金额
----------- ----------- ----------- ----------- -----------
2008 2 330 1 1
2009 2 990 0 0(2 行受影响)
*/
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([ID] int,[年份] int,[状态] varchar(4),[金额] int)
insert [tb]
select 1,2008,'申请',110 union all
select 2,2008,'已批',220 union all
select 3,2008,'已退',330 union all
select 4,2009,'申请',440 union all
select 5,2009,'不批',550
/*
年份 受理条数 受理金额 已退条数 已退金额
2008 3 660 1 330
2009 2 990 0 0受理 = 申请 + 已批 + 不批
已退 = 已退
*/
select 年份,
受理条数=sum(case when [状态]='申请' or [状态]='已批' or [状态]='不批' then 1 else 0 end),
受理金额=sum(case when [状态]='申请' or [状态]='已批' or [状态]='不批' then [金额] else 0 end),
已退条数=sum(case when [状态]='已退' then 1 else 0 end),
已退金额=sum(case when [状态]='已退' then [金额] else 0 end)
from [tb]
group by 年份/*
年份 受理条数 受理金额 已退条数 已退金额
----------- ----------- ----------- ----------- -----------
2008 2 330 1 330
2009 2 990 0 0(2 行受影响)*/