我有一张如下表格
Item Name | Date | Previous Data | Updated Data
Unit 1 | 1-Jul-2013 | 500 | 550
Unit 1 | 1-Aug-2013 | 550 | 550
Unit 1 | 1-Sep-2013 | 450 | 600
Unit 1 | 1-Oct-2013 | 600 | 550
我希望使用查询显示它们,如下所示
Title | Jul | Aug | Sep | Oct
Prev. Data| 500 | 550 | 450 | 600
Upd. Data | 550 | 550 | 600 | 550
之前我使用UNION
确保表格符合我的要求,但我想知道是否有更简单的方法。
我正在使用SQL Server 2008 R2
答案 0 :(得分:0)
首先,您需要将2列[Previous Data]
和[Updated Date]
转换为行,然后才能在PIVOT
列上使用Date
Select col,
[1] as Jan,
[2] Feb,
[3] Mar,
[4] Apr,
[5] May,
[6] Jun,
[7] Jul,
[8] Aug,
[9] Sep,
[10] Oct,
[11] Nov,
[12] Dec
from
(
select month(Date) as TMonth, col, value
from Table1
cross apply
(
select 'Previous Data', [Previous Data]
union all
select 'Updated Date', [Updated Data]
) c(col, value)
)a
PIVOT
(
Sum(value)
for Tmonth in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
)pvt
答案 1 :(得分:0)
请试试这个........
select 'PreviousData' as Title,Jul,Aug,Sep,Oct from
(
select a.itemname,left(datename(mm,convert(date,a.date)),3) [date]
,a.previousdata from @tab a
) srs
pivot
(
sum(previousdata) for [date] in (jul,aug,sep,oct)
) pt
union all
select 'UpdatedData' as Title,Jul,Aug,Sep,Oct from
(
select a.itemname,left(datename(mm,convert(date,a.date)),3) [date]
,a.Updateddata from @tab a
) srs
pivot
(
sum(Updateddata) for [date] in (jul,aug,sep,oct)
) pt