[]求一条高难度行列互换的语句
[在线等]求一条高难度行列互换的语句
问题很简单,见下表。把源表变成目标表即可,请高手赐教:
源表
类型 数量 金额
衣服 200 840
裤子 100 300
鞋子 170 340
目标表
类型 衣服 裤子 鞋子
数量 200 100 170
金额 840 300 340
------解决方案--------------------
又见90°旋转。精华帖子里面N多.
------解决方案--------------------
问题很简单,见下表。把源表变成目标表即可,请高手赐教:
源表
类型 数量 金额
衣服 200 840
裤子 100 300
鞋子 170 340
目标表
类型 衣服 裤子 鞋子
数量 200 100 170
金额 840 300 340
------解决方案--------------------
又见90°旋转。精华帖子里面N多.
------解决方案--------------------
- SQL code
--> 测试数据:[t] if object_id('[t]') is not null drop table [t] go create table [t]([类型] varchar(4),[数量] int,[金额] int) insert [t] select '衣服',200,840 union all select '裤子',100,300 union all select '鞋子',170,340 --------------开始查询-------------------------- select '数量' as col1 , max(case when 类型='衣服' then 数量 end) as 衣服, max(case when 类型='裤子' then 数量 end) as 裤子, max(case when 类型='鞋子' then 数量 end) as 鞋子 from [t] union all select '金额' as col1 , max(case when 类型='衣服' then 金额 end) as 衣服, max(case when 类型='裤子' then 金额 end) as 裤子, max(case when 类型='鞋子' then 金额 end) as 鞋子 from [t] ----------------结果---------------------------- /* col1 衣服 裤子 鞋子 ---- ----------- ----------- ----------- 数量 200 100 170 金额 840 300 340 */
------解决方案--------------------
- SQL code
create table 源表 (类型 varchar(6), 数量 int, 金额 int) insert into 源表 select '衣服', 200, 840 union all select '裤子', 100, 300 union all select '鞋子', 170, 340 select * from 源表 类型 数量 金额 ------ ----------- ----------- 衣服 200 840 裤子 100 300 鞋子 170 340 select col,[衣服],[裤子],[鞋子] into 目标表 from (select 类型,b.col,b.c from 源表 a unpivot(c for col in ([数量],[金额])) b) c pivot(max(c) for 类型 in ([衣服],[裤子],[鞋子])) d select * from 目标表 col 衣服 裤子 鞋子 ------------- ----------- ----------- ----------- 金额 840 300 340 数量 200 100 170 (2 row(s) affected)
------解决方案--------------------
- SQL code
--> 测试数据:[源表] if object_id('[源表]') is not null drop table [源表] create table [源表]([类型] varchar(4),[数量] int,[金额] int) insert [源表] select '衣服',200,840 union all select '裤子',100,300 union all select '鞋子',170,340 select 类型='数量',* from (select [类型],[数量] from [源表] )a pivot (max(数量) for [类型] in([衣服],[裤子],[鞋子]))b union all select 类型='金额',* from (select [类型],[金额] from [源表] )a pivot (max(金额) for [类型] in([衣服],[裤子],[鞋子]))b /* 类型 衣服 裤子 鞋子 数量 200 100 170 金额 840 300 340 */