22,209
社区成员
发帖
与我相关
我的任务
分享
create table 一张表
(销售时间 varchar(20),销售品种 varchar(10),零售价格 int)
insert into 一张表
select '2月1日', 'A', 20 union all
select '2月1日', 'B', 20 union all
select '2月1日', 'C', 20 union all
select '2月2日', 'A', 21 union all
select '2月2日', 'B', 21 union all
select '2月2日', 'C', 21
declare @tsql varchar(6000)
select @tsql=isnull(@tsql+',','')+'['+销售时间+']'
from (select distinct 销售时间 from 一张表) t
select @tsql='select 销售品种,'+@tsql
+' from 一张表 '
+ ' pivot(max(零售价格) for 销售时间 in('+@tsql+')) t '
exec(@tsql)
/*
销售品种 2月1日 2月2日
--------------- ------------- -------------
A 20 21
B 20 21
C 20 21
(3 row(s) affected)
*/
SELECT
销售品种
,MAX(CASE WHEN 销售时间='2月1日' THEN 零售价格 END) AS [2月1日]
,MAX(CASE WHEN 销售时间='2月2日' THEN 零售价格 END) AS [2月2日]
FROM TABLE1
GROUP BY 销售品种