有一张全年的工资表,要求按工资总额区间统计
分公司编号 部门编号 姓名 发放月份 工资
01 001 张展 201101 10000
01 001 张展 201105 20000
01 002 李四 201101 50000
02 001 小红 201105 90000
02 003 晓宇 201102 30000
02 001 小黄 201102 30000
统计的结果年收入额 人数
0-3万 3
3-5万 1
5-10万 1
分公司编号 部门编号 姓名 发放月份 工资
01 001 张展 201101 10000
01 001 张展 201105 20000
01 002 李四 201101 50000
02 001 小红 201105 90000
02 003 晓宇 201102 30000
02 001 小黄 201102 30000
统计的结果年收入额 人数
0-3万 3
3-5万 1
5-10万 1
go
create table [tb]([分公司编号] varchar(2),[部门编号] varchar(3),[姓名] varchar(4),[发放月份] int,[工资] int)
insert [tb]
select '01','001','张展',201101,10000 union all
select '01','001','张展',201105,20000 union all
select '01','002','李四',201101,50000 union all
select '02','001','小红',201105,90000 union all
select '02','003','晓宇',201102,30000 union all
select '02','001','小黄',201102,30000
goselect
case
when 工资>0 and 工资<=30000 then '0-3万'
when 工资>30000 and 工资<=50000 then '3-5万'
when 工资>50000 and 工资<=100000 then '5-10万'
end as 年收入额,
count(1) as 人数
from(
select 分公司编号,部门编号,姓名,sum(工资) as 工资
from tb
where left(发放月份,4)='2011'
group by 分公司编号,部门编号,姓名
) t
group by
case
when 工资>0 and 工资<=30000 then '0-3万'
when 工资>30000 and 工资<=50000 then '3-5万'
when 工资>50000 and 工资<=100000 then '5-10万'
end/**
年收入额 人数
------ -----------
0-3万 3
3-5万 1
5-10万 1(3 行受影响)
**/
select '3-5万' as 年收入额,sum(case when [工资]>30000 and [工资]<=50000 then 1 else 0 end ) as 人数 from [tb] union all
select '5-10万' as 年收入额,sum(case when [工资]>50000 and [工资]<=100000 then 1 else 0 end ) as 人数 from [tb]
年收入额 人数
------ -----------
0-3万 4
3-5万 1
5-10万 1(3 row(s) affected)
go
create table [tb]([分公司编号] varchar(2),[部门编号] varchar(3),[姓名] varchar(4),[发放月份] int,[工资] int)
insert [tb]
select '01','001','张展',201101,10000 union all
select '01','001','张展',201105,20000 union all
select '01','002','李四',201101,50000 union all
select '02','001','小红',201105,90000 union all
select '02','003','晓宇',201102,30000 union all
select '02','001','小黄',201102,30000
go;with temp as(
select distinct [分公司编号],[部门编号],[姓名],
sum([工资]) over(partition by [分公司编号],[部门编号],[姓名]) 总工资 from tb
)
select
case when [总工资]>0 and [总工资]<=30000 then '0-3万'
when [总工资]>30000 and [总工资]<=50000 then '3-5万'
when 总工资>50000 and 总工资<=100000 then '5-10万' end as 年收入额,
COUNT(*) [人数]
from temp
group by [总工资]/*
年收入额 人数
0-3万 3
3-5万 1
5-10万 1
*/
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([分公司编号] varchar(2),[部门编号] varchar(3),[姓名] varchar(4),[发放月份] int,[工资] int)
insert [tb]
select '01','001','张展',201101,10000 union all
select '01','001','张展',201105,20000 union all
select '01','002','李四',201101,50000 union all
select '02','001','小红',201105,90000 union all
select '02','003','晓宇',201102,30000 union all
select '02','001','小黄',201102,30000
go
SELECT CASE WHEN [总工资] <= 30000 THEN '0-3万'
WHEN [总工资] <= 50000 THEN '3-5万'
WHEN [总工资] <= 100000 THEN '5-10万' END AS 年收入额
, count (1) AS [人数]
FROM (
SELECT DISTINCT [姓名]
, sum ([工资]) [总工资]
FROM tb
GROUP BY [姓名]
)t
group by [总工资]------
0-3万 3
3-5万 1
5-10万 1
------