Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Server 2008中的行作为列_Sql_Sql Server_Sql Server 2008 - Fatal编程技术网

SQL Server 2008中的行作为列

SQL Server 2008中的行作为列,sql,sql-server,sql-server-2008,Sql,Sql Server,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

我正在使用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
还有一种方法:


请提供您当前的查询,如果可能,请以更方便的方式组织生成的数据,以便使用标题进行阅读,分隔符非常感谢它的帮助..如何使用此查询获取列式总计添加另一个SUMvalue而不进行任何测试将为您提供总计更新答案。抱歉,我错误地提到了列式总计,我希望使用行式总计获取行式总计更新答案。