行转列...就是CASE WHEN END或者PIVOT ,unpivot,union all的联合
虽然楼主已结贴,还是把我的举例说完吧 create table tb( gid int, col1 varchar(10), col2 dec(18,2) ) goinsert tb select 1,'a',10 union all select 1,'b',12 union all select 1,'c',56 union all select 2,'a',32 union all select 2,'b',6 union all select 3,'a',87 go-->把每行中col1列中指定的值对应的col2列中的值作为一列,其他不符合条件的可以用else来指定值,不指定默认为null select gid, case when col1='a' then col2 else 0 end as a, --col1列中值为'a'对应的col2的值,不符合条件的用0代替 case when col1='b' then col2 end as b, --不指定不符合条件的值,默认为null case when col1='c' then col2 end as c from tb /** gid a b c ----------- -------------------- -------------------- -------------------- 1 10.00 NULL NULL 1 .00 12.00 NULL 1 .00 NULL 56.00 2 32.00 NULL NULL 2 .00 6.00 NULL 3 87.00 NULL NULL(所影响的行数为 6 行) **/-->然后对以上值进行分组统计 select gid, sum(case when col1='a' then col2 else 0 end) as a, sum(case when col1='b' then col2 end) as b, sum(case when col1='c' then col2 end) as c from tb group by gid/** gid a b c ----------- ---------------------------------------- ---------------------------------------- ---------------------------------------- 1 10.00 12.00 56.00 2 32.00 6.00 NULL 3 87.00 NULL NULL(所影响的行数为 3 行)警告: 聚合或其它 SET 操作消除了空值。 **/
create table tb(
gid int,
col1 varchar(10),
col2 dec(18,2)
)
goinsert tb
select 1,'a',10 union all
select 1,'b',12 union all
select 1,'c',56 union all
select 2,'a',32 union all
select 2,'b',6 union all
select 3,'a',87
go-->把每行中col1列中指定的值对应的col2列中的值作为一列,其他不符合条件的可以用else来指定值,不指定默认为null
select gid,
case when col1='a' then col2 else 0 end as a, --col1列中值为'a'对应的col2的值,不符合条件的用0代替
case when col1='b' then col2 end as b, --不指定不符合条件的值,默认为null
case when col1='c' then col2 end as c
from tb
/**
gid a b c
----------- -------------------- -------------------- --------------------
1 10.00 NULL NULL
1 .00 12.00 NULL
1 .00 NULL 56.00
2 32.00 NULL NULL
2 .00 6.00 NULL
3 87.00 NULL NULL(所影响的行数为 6 行)
**/-->然后对以上值进行分组统计
select gid,
sum(case when col1='a' then col2 else 0 end) as a,
sum(case when col1='b' then col2 end) as b,
sum(case when col1='c' then col2 end) as c
from tb
group by gid/**
gid a b c
----------- ---------------------------------------- ---------------------------------------- ----------------------------------------
1 10.00 12.00 56.00
2 32.00 6.00 NULL
3 87.00 NULL NULL(所影响的行数为 3 行)警告: 聚合或其它 SET 操作消除了空值。
**/