首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

[]求一条高难度行列互换的语句

2012-05-04 
[在线等]求一条高难度行列互换的语句问题很简单,见下表。把源表变成目标表即可,请高手赐教:源表类型数量金

[在线等]求一条高难度行列互换的语句
问题很简单,见下表。把源表变成目标表即可,请高手赐教:

源表
类型数量金额
衣服200840
裤子100300
鞋子170340


目标表
类型衣服裤子鞋子
数量200100170
金额840300340


[解决办法]
又见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 allselect '裤子',100,300 union allselect '鞋子',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 allselect '金额' 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         340select col,[衣服],[裤子],[鞋子]into 目标表from(select 类型,b.col,b.cfrom 源表 aunpivot(c for col in ([数量],[金额])) b) cpivot(max(c) for 类型 in ([衣服],[裤子],[鞋子])) dselect * 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 allselect '裤子',100,300 union allselect '鞋子',170,340select 类型='数量',*from (select [类型],[数量] from  [源表] )apivot     (max(数量) for [类型] in([衣服],[裤子],[鞋子]))bunion allselect 类型='金额',*from (select [类型],[金额] from  [源表] )apivot     (max(金额) for [类型] in([衣服],[裤子],[鞋子]))b/*类型    衣服    裤子    鞋子数量    200    100    170金额    840    300    340*/ 

热点排行