我遇到了问题,我试图在我的查询中使用PIVOT并且没有任何结果。现在我有一张看起来像的表:
Category Month Value
A August 10
B August 19
C August 15
A September 20
B September 23
C September 25
A October 24
B October 87
C October 44
我想以这种方式看待:
Category August September October
A 10 20 24
B 19 23 87
C 15 25 47
在我的选择中是这样的:
Select cat_name, CAST(month AS VARCHAR(20)), value from dbo.table1.
_
select * from (
select ft.categoryData as [category], CAST(fft.date AS VARCHAR(20)) as [month], tt.value as [value] from firstt ft
join secondt st on ft.id = st.id
join thirdt tt on ft.id = tt.type_id
join fourtht fft on ft.id = fft.category_id
where ft.date between '2015-07-01' and '2015-09-01' and ft.country = 'EUR'
group by fft.date, ft.categoryData, tt.value
) as t
PIVOT (
max(value)
for [date] in ([jul], [aug], [sept])
) as pvt
答案 0 :(得分:1)
通过使用pivot我们可以在下面写下查询和语法,请点击下面的链接 如上所述
SELECT *
FROM TABLE_NAME
PIVOT(MAX(VALUE) FOR MONTH IN (
[AUGUST]
,[SEPTEMBER]
,[OCTOBER]
)) AS
PIVOT_SALES
out put是
答案 1 :(得分:0)
尝试Conditional Aggregate
。
select Category,
max(case when Month = 'August' then Value END) as August,
max(case when Month = 'September' then Value END) as September,
max(case when Month = 'October' then Value END) as October
from Yourtable
Group by Category
或使用Pivot
select *
from Yourtable
pivot (max(Value) For Month in ([August],[September],[October]))pv
当月份列中的值未知时使用动态sql
declare @sql nvarchar(max)= '',
@col_list varchar(max)=''
set @col_list =(select distinct quotename(Month)+',' from yourtable for xml path (''))
set @col_list = left(@col_list,len(@col_list)-1)
set @sql = '
select *
from yourtable
pivot (max(Value) For Month in ('+@col_list+'))pv'
exec sp_executesql @sql