SQL 分类统计查询---敬请高手指点
现有3个表:
A表:
id name
001 苏州
002 杭州
003 郑州
004 常州
.......
B表:
pno cs
1 张三
2 李四
3 王二
4 麻子
......
C表
加工度 区域代码 人员代码 状况
P0 001 1 N
P1 001 1 N
P2 003 3 Y
P1 004 2 C
P3 001 1 C
P0 003 2 Y
P2 001 1 c
.......
希望查询结果:
P0 P1 P2 P3 合计
区域 人员 Y N C Y N C Y N C Y N C Y N C
苏州 张三 1 1 1 1 0 2 2
以上我只是一个例子。
简而言之:3个表是相互关联, 要查询的结果是 每个区域所对应的人员 以及相应的加工度的状况的个数,还有合计出每个状况的 总和
怎么分类统计啊 这个太复杂了,偶不会!!!
分太少了
[解决办法]
create table A(id int, name varchar(20))
insert into A
select '001', '苏州'
union all select '002','杭州'
union all select '003','郑州'
union all select '004','常州'
create table B(pno int, cs varchar(20))
insert into B
select 1, '张三'
union all select 2, '李四'
union all select 3, '王二'
union all select 4, '麻子'
create table C(
加工度 varchar(20),
区域代码 varchar(10),
人员代码 int,
状况 varchar(10)
)
insert into c
select 'P0' , '001', 1, 'N'
union all select 'P1' ,'001', 1, 'N'
union all select 'P2' ,'003', 3, 'Y'
union all select 'P1' ,'004', 2, 'C'
union all select 'P3' ,'001', 1, 'C'
union all select 'P0' ,'003', 2, 'Y'
union all select 'P2' ,'001', 1, 'c'
select a.name,
b.cs,
count(case when c.加工度 = 'P0' AND c.状况='Y' then 1 else null end) as P0_Y,
count(case when c.加工度 = 'P0' AND c.状况='N' then 1 else null end) as P0_N,
count(case when c.加工度 = 'P0' AND c.状况='C' then 1 else null end) as P0_C,
count(case when c.加工度 = 'P1' AND c.状况='Y' then 1 else null end) as P1_Y,
count(case when c.加工度 = 'P1' AND c.状况='N' then 1 else null end) as P1_N,
count(case when c.加工度 = 'P1' AND c.状况='C' then 1 else null end) as P1_C,
count(case when c.加工度 = 'P2' AND c.状况='Y' then 1 else null end) as P2_Y,
count(case when c.加工度 = 'P2' AND c.状况='N' then 1 else null end) as P2_N,
count(case when c.加工度 = 'P2' AND c.状况='C' then 1 else null end) as P2_C,
count(case when c.加工度 = 'P3' AND c.状况='Y' then 1 else null end) as P3_Y,
count(case when c.加工度 = 'P3' AND c.状况='N' then 1 else null end) as P3_N,
count(case when c.加工度 = 'P3' AND c.状况='C' then 1 else null end) as P3_C,
count(case when c.加工度 in ('P0','P1','P2','P3') AND c.状况='Y' then '1' else null end) as 总计_Y,
count(case when c.加工度 in ('P0','P1','P2','P3') AND c.状况='N' then 1 else null end) as 总计_N,
count(case when c.加工度 in ('P0','P1','P2','P3') AND c.状况='C' then 1 else null end) as 总计_C
from c
inner join a
on a.id = c.区域代码
inner join b
on b.pno = c.人员代码
group by a.name,b.cs
/*
namecsP0_YP0_NP0_CP1_YP1_NP1_CP2_YP2_NP2_CP3_YP3_NP3_C总计_Y总计_N总计_C
常州李四000001000000001
郑州李四100000000000100
郑州王二000000100000100
苏州张三010010001001022
*/