本文转载:http://www.cnblogs.com/lxblog/archive/2012/09/29/2708128.html
问题描述:
假如有一表结构和数据如下:
C1 | C2 | C3 | C4 | C5 |
1 | 2 | 6 | 3 | 4 |
2 | 2 | 3 | 4 | 5 |
0 | 3 | 6 | 2 | 8 |
经过sql查询后输出的结果集为:(字段后面增加聚合[最大值] [最小值] [>=5的值个数])
C1 | C2 | C3 | C4 | C5 | Max | Min | Count(>=5) |
1 | 2 | 6 | 3 | 4 | 6 | 1 | 1 |
2 | 2 | 3 | 4 | 5 | 5 | 2 | 1 |
0 | 3 | 6 | 2 | 8 | 8 | 2 | 2 |
实现该结果的SQL 脚本如下:
/* 作 者:<Rising_Sun> 创建日期:<2012-9-29> 功 能:<实现表横向聚合> */ DECLARE @t TABLE(C1 int,C2 int,C3 int,C4 int,C5 int) INSERT INTO @t VALUES(1,2,6,3,4) INSERT INTO @t VALUES(2,2,3,4,5) INSERT INTO @t VALUES(0,3,6,2,8) --查询 SELECT *, [min] = ( SELECT MIN(v) FROM( SELECT v=A.C1 UNION SELECT v=A.C2 UNION SELECT v=A.C3 UNION SELECT v=A.C4 UNION SELECT v=A.C5 )B), [max] = ( SELECT MAX(v) FROM( SELECT v=A.C1 UNION SELECT v=A.C2 UNION SELECT v=A.C3 UNION SELECT v=A.C4 UNION SELECT v=A.C5 )B), [count>=5] = ( SELECT COUNT(*) FROM( SELECT v=A.C1 UNION SELECT v=A.C2 UNION SELECT v=A.C3 UNION SELECT v=A.C4 UNION SELECT v=A.C5 )B WHERE v>=5) FROM @t A
执行结果如下图所示: