简体   繁体   English

SQL Server 2008数据透视表

[英]sql server 2008 pivot table

I have the following table ... 我有下表...

GROUP   Number  Sum     SOURCE
a           1   -2503   WTH
a           2   -180    DET
a           3   -156    PLY
a           4   -99     DET
a           5   -252    DET

Which I'd like to present as follows ... 我想提出如下......

GROUP   Number  Sum      DET    PLY     WTH
a           1   -2503                   -2503
a           2   -180    -180        
a           3   -156           -156 
a           4   -99     -99     
a           5   -252    -252        

Here is what I've tried (unsuccessfully) using PIVOT ... 这是我尝试使用PIVOT(未成功)...

SELECT
    [GROUP]
    ,Number
    ,Opening_Val
    ,[Sum]
    ,DET
    ,PLY
    ,WTH
FROM
(SELECT 
     IA.GROUP_CD
    ,IA.Number
    ,IA.[sum]
    ,Src
FROM dbo.##Inter_App IA
GROUP BY IA.[GROUP]
    ,IA.Number
    ,IA.[sum]
    ,Src ) query
PIVOT 
(   Sum(IA.[Sum])
    For Src in (DET, PLY, WTH)
) pvt

Ideally, I'll like not to limit the columns to (DET, PLY, WTH) as there may be more SOURCE's that I'm not aware of. 理想情况下,我不希望将列限制为(DET,PLY和WTH),因为可能还有更多我不知道的SOURCE。

Any help appreciated. 任何帮助赞赏。

Thanks, James 谢谢,詹姆斯

You have a few things wrong with your existing query. 您现有的查询存在一些问题。

First, I'm not sure why in your subquery you are using a GROUP BY on all of the columns. 首先,我不确定为什么在子查询中对所有列都使用GROUP BY。 This is not necessary unless you know you have duplicates that you don't want in the final result. 除非您知道最终结果中不希望有重复项,否则这不是必需的。

Second, you are trying to display the [sum] column in the final select list but you are also aggregating this data in the PIVOT -- Sum(IA.[Sum]) -- you can't aggregate the data and display this value unless your subquery has this column listed twice. 其次,您试图在最终选择列表中显示[sum]列,但您也在PIVOT - Sum(IA.[Sum])聚合此数据 - 您无法聚合数据并显示此值除非您的子查询列出了此列两次。

Third, the aggregation used in the PIVOT is referencing the IA table alias - this alias is not available outside of the subquery so that syntax will not work either. 第三,PIVOT中使用的聚合正在引用IA表别名-该别名在子查询之外不可用,因此语法也将不起作用。

I would alter your query to use the following: 我会改变您的查询以使用以下内容:

select [group], [number], [sum], DET, PLY, WTH
from
(
  select [group], [number], 
    [sum], 
    [sum] pivsum, SOURCE
  from dbo.Inter_App
) d
pivot
(
  sum(pivsum)
  for SOURCE in (DET, PLY, WTH)
) piv;

See SQL Fiddle with Demo . 请参阅SQL Fiddle with Demo You'll notice that the subquery has two columns with the [sum] - one of these I gave an alias pivsum - this will be used for the aggregation in the PIVOT, the other column will be used in the final select list. 您会注意到子查询有两列[sum] - 其中一列我给了别名pivsum - 这将用于PIVOT中的聚合,另一列将用于最终选择列表。

Finally, you stated that you might have an unknown number of Source values, if that is the case then you will need to use dynamic SQL to generate the result: 最后,您声明您可能具有未知数量的Source值,如果是这种情况,那么您将需要使用动态SQL来生成结果:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(SOURCE) 
                    from Inter_App
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT [group], [number], 
                [sum], ' + @cols + ' 
            from 
            (
              select [group], [number], 
                [sum], 
                [sum] pivsum, SOURCE
              from dbo.Inter_App
            ) x
            pivot 
            (
                sum(pivsum)
                for SOURCE in (' + @cols + ')
            ) p '

execute sp_executesql @query;

See SQL Fiddle with Demo . 请参阅SQL Fiddle with Demo Both versions give a result: 这两个版本都给出结果:

| GROUP | NUMBER |   SUM |    DET |    PLY |    WTH |
|-------|--------|-------|--------|--------|--------|
|     a |      1 | -2503 | (null) | (null) |  -2503 |
|     a |      2 |  -180 |   -180 | (null) | (null) |
|     a |      3 |  -156 | (null) |   -156 | (null) |
|     a |      4 |   -99 |    -99 | (null) | (null) |
|     a |      5 |  -252 |   -252 | (null) | (null) |

You made your attempt too complicated :). 你让你的尝试太复杂了:) Also, pick other names for your columns instead of sum, group and number, because not only those are sql-syntax keywords, it also makes the queries harder to read (eg sum([sum]), group by [group]). 另外,为列选择其他名称,而不是总和,组和数字,因为不仅这些是sql语法关键字,而且还使查询更难阅读(例如,总和[[sum]),按[group]分组)。

drop table #temp
GO
select 
    *
into #temp
from (
    select 'a' as [group],1 as [number],'-2503' as [sum],'WTH' as [source] union all
    select 'a',2,-180,'DET' union all
    select 'a',3,-156,'PLY' union all
    select 'a',4,-99,'DET' union all
    select 'a',5,-252,'DET' 
) x
GO   

select 
    [group], [number], 
    det, ply, wth
from #temp
pivot (
    sum([sum]) for [source] in (det,ply,wth)
) x

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

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