沧海笑的艺术人生

沧海一声笑, 滔滔两岸潮,浮沉随浪只记今朝
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

T-SQL经典语句搜藏(三)

Posted on 2005-06-22 11:51  沧海笑  阅读(637)  评论(0编辑  收藏  举报

交叉表实现一例
问题 :
源表数据:   
ID    NAME    CODE
1       A          AA
2       A          BB
3       B          CC
4       B          DD
5       C          EE
6       C          FF
7       D          GG
8       D          HH
9       E          II
10     E          JJ
希望统计成如下格式:
CODE       A           C           D           E           F           合计   
---------- ----------- ----------- ----------- ----------- ----------- -----
AA         1           0           0           0           0           10%
BB         1           0           0           0           0           10%
CC         0           1           0           0           0           10%
DD         0           1           0           0           0           10%
EE         0           0           1           0           0           10%
FF         0           0           1           0           0           10%
GG         0           0           0           1           0           10%
HH         0           0           0           1           0           10%
II         0           0           0           0           1           10%
JJ         0           0           0           0           1           10%

实现步骤如下:
--建立测试数据
declare @tmp1 table
(
 id int,
 name varchar(10),
 code varchar(10)
)
insert into @tmp1
select 1,'A','AA'
UNION
select 2,'A','BB'
UNION
select 3,'B','CC'
UNION
select 4,'B','DD'
UNION
select 5,'C','EE'
UNION
select 6,'C','FF'
UNION
select 7,'D','GG'
UNION
select 8,'D','HH'
UNION
select 9,'E','II'
UNION
select 10,'E','JJ'

--返回结果
SELECT  CODE,
 sum(A) as 'A',
 sum(B) as 'C',
 sum(C) as 'D',
 sum(D) as 'E',
 sum(E) as 'F',
 left(CAST(COUNT(CODE) AS DECIMAL(10,2))/(SELECT COUNT(*) FROM @TMP1)*100,2) +'%' AS '合计'
FROM
(SELECT CODE ,
 CASE WHEN NAME='A' THEN count(CODE) ELSE 0 end as A,
 CASE WHEN NAME='B' THEN count(CODE) ELSE 0 end AS B,
 CASE WHEN NAME='C' THEN count(CODE) ELSE 0 end AS C,
 CASE WHEN NAME='D' THEN count(CODE) ELSE 0 end AS D,
 CASE WHEN NAME='E' THEN count(CODE) ELSE 0 end AS E
FROM @tmp1
GROUP BY CODE,name) AS C
GROUP   BY CODE