我有一张桌子,简单的选择给出如下
我想写一条选择语句输出如下
有人能帮我吗...
因为你基本上旋转你当前的列Sale
,Income
并Profit
进入行,然后将month
值列,那么你会想先unpivot的当前列,然后转动的月份。
根据您的SQL Server版本,有几种方法可以取消数据透视。您可以使用UNPIVOT函数或交叉应用:
select month, type, value
from yourtable
cross apply
(
select 'Sale', sale union all
select 'Income', Income union all
select 'Profit', Profit
) c (type, value)
请参见带有演示的SQL Fiddle。这会将您当前的数据转换为:
| MONTH | TYPE | VALUE |
|-------|--------|-------|
| Jan | Sale | 100 |
| Jan | Income | 50 |
| Jan | Profit | 10 |
| Feb | Sale | 20 |
| Feb | Income | 40 |
然后,您可以使用PIVOT函数将月份转换为列标题。
select type, Jan, Feb, Mar, Apr
from
(
select month, type, value
from yourtable
cross apply
(
select 'Sale', sale union all
select 'Income', Income union all
select 'Profit', Profit
) c (type, value)
) d
pivot
(
sum(value)
for month in (Jan, Feb, Mar, Apr)
) piv;
请参见带有演示的SQL Fiddle。
如果您的月份数未知,则可以使用动态SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct N',' + QUOTENAME(Month)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT type, ' + @cols + N'
from
(
select month, type, value
from yourtable
cross apply
(
select ''Sale'', sale union all
select ''Income'', Income union all
select ''Profit'', Profit
) c (type, value)
) x
pivot
(
sum(value)
for month in (' + @cols + N')
) p '
execute sp_executesql @query;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句