繁体   English   中英

在SQL Server 2008中作为列

[英]Row as column in SQL Server 2008

我正在使用SQL Server 2008.我有一个临时表,它返回此结果

Location      Month        value
US          January         10
US          February        10
US          March           10
US          April           10
US          May             10
US          June            10
UK          January         10
UK          January         10
UK          February        10
UK          February        10
UK          March           10
UK          March           10
UK          April           10
UK          April           10
UK          May             10
UK          May             10
UK          June            10
UK          June            10

我想得到如下结果

Location    January February    March   Q1  April   May June    Q2
US              10        10       10   30     10    10   10    30
UK              20        20       20   60     20    20   20    60

如何使用SQL Server 2008查询以获得上述结果?

您可以使用此查询,您必须完成它以满足您所有缺少的月/季度的需求:

select  Location
        ,sum(case when [Month]  = 'January'  then value else 0 end)  as January
        ,sum(case when [Month]  = 'February' then value else 0 end)  as February
        ,sum(case when [Month]  = 'March'    then value else 0 end)  as March
        ,sum(case when [Month] in ( 'January', 'February', 'March')
                                             then value else 0 end) as Q1
        ...
        -- Repeat months...
        ...
        ,sum(value) as AllMonthTotal
from    myTempTable
group by Location

-- UNION to get rowwise total
union
select  'TOTAL'
        ,sum(case when [Month]  = 'January'  then value else 0 end)  as January
        ,sum(case when [Month]  = 'February' then value else 0 end)  as February
        ,sum(case when [Month]  = 'March'    then value else 0 end)  as March
        ,sum(case when [Month] in ( 'January', 'February', 'March')
                                             then value else 0 end) as Q1
        ...
        -- Repeat months...
        ...
        ,sum(value) as AllMonthTotal
from    myTempTable

还有PIVOT方法:

在SQL Server 2008中使用PIVOT

MSSQL动态数据透视表列值到列标题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM