日期:2014-05-19  浏览次数:20598 次

倾囊求一个复杂的统计SQL
表AA
区域, 大类, 功能1, 功能2, 货号, 规格, 销售数量
1, IOPD, sing, A, 1234, 11-11, 2
1, IOPD, sing, A, 1234, 11-12, 2
1, IOPD, sing, A, 6780, 11-22, 3
1, IOPD, sing, A, 1234, 11-11, 5
1, IOPD, sing, B, 1234, 11-11, 5
1, IOPD, sing, B, 1234, 11-12, 6
2, IOPD, sing, A, 1234, 11-11, 2
2, IOPD, sing, A, 1234, 11-12, 2
2, IOPD, sing, A, 6780, 11-22, 3
2, IOPD, sing, A, 1234, 11-11, 5
2, IOPD, sing, B, 1234, 11-11, 5
2, IOPD, sing, B, 1234, 11-12, 6

。。。。。。。。。。。。。。。

要求统计如下:
大类,功能1\功能2,区域1货号数量,区域1(货号+规格数量),销售数量   ,区域2货号数量,区域2(货号+规格数量),区域2销售数量
IOPD, sing\A, 2, 4, 12,     2, 4, 12
IOPD, sing\B, 1, 2, 11,               2, 4, 12
。。。。。。。。。


------解决方案--------------------
declare @a table(区域 int, 大类 char(4), 功能1 char(4), 功能2 char(1), 货号 int, 规格 varchar(5), 销售数量 int)
insert @a select 1, 'IOPD ', 'sing ', 'A ',1234, '11-11 ', 2
union all select 1, 'IOPD ', 'sing ', 'A ',1234, '11-12 ', 2
union all select 1, 'IOPD ', 'sing ', 'A ',6780, '11-22 ', 3
union all select 1, 'IOPD ', 'sing ', 'A ',1234, '11-11 ', 5
union all select 1, 'IOPD ', 'sing ', 'B ',1234, '11-11 ', 5
union all select 1, 'IOPD ', 'sing ', 'B ',1234, '11-12 ', 6
union all select 2, 'IOPD ', 'sing ', 'A ',1234, '11-11 ', 2
union all select 2, 'IOPD ', 'sing ', 'A ',1234, '11-12 ', 2
union all select 2, 'IOPD ', 'sing ', 'A ',6780, '11-22 ', 3
union all select 2, 'IOPD ', 'sing ', 'A ',1234, '11-11 ', 5
union all select 2, 'IOPD ', 'sing ', 'B ',1234, '11-11 ', 5
union all select 2, 'IOPD ', 'sing ', 'B ',1234, '11-12 ', 6

select 大类,功能1+ '\ '+功能2,
区域1货号数量=(select count(distinct 货号) from @a where 大类=a.大类 and 功能1=a.功能1 and 功能2=a.功能2 and 区域=1),
区域1=(select count(distinct ltrim(货号)+规格) from @a where 大类=a.大类 and 功能1=a.功能1 and 功能2=a.功能2 and 区域=1),
销售数量=(select sum(销售数量) from @a where 大类=a.大类 and 功能1=a.功能1 and 功能2=a.功能2 and 区域=1),
区域2货号数量=(select count(distinct 货号) from @a where 大类=a.大类 and 功能1=a.功能1 and 功能2=a.功能2 and 区域=2),
区域2=(select count(distinct ltrim(货号)+规格) from @a where 大类=a.大类 and 功能1=a.功能1 and 功能2=a.功能2 and 区域=2),
区域2销售数量=(select sum(销售数量) from @a where 大类=a.大类 and 功能1=a.功能1 and 功能2=a.功能2 and 区域=2)
from @a a
group by 大类,功能1,功能2
------解决方案--------------------
都是交叉表的问题。
之前已经很多人问过相似的问题了。