SQL 查询两个 PIVOT 列组合
Posted
技术标签:
【中文标题】SQL 查询两个 PIVOT 列组合【英文标题】:SQL query two PIVOT columns combine 【发布时间】:2020-06-19 09:50:08 【问题描述】:select pvtMonth.CardName, [1] as [Jan Sales], [2] as [Feb Sales], [3] as [Mar Sales], [4] as [Apr Sales], [5] as [May Sales],
[6] as [Jun Sales], [7] as [Jul Sales], [8] as [Aug Sales], [9] as [Sep Sales], [10] as [Oct Sales], [11] as [Nov Sales], [12] as [Dec Sales] from
(
select X.CardName, SUM(X.[Total Sales S$]) as [Sales $] , X.Month from Data X group by X.CardName ,X.Month
) X PIVOT
(
sum(X.[Sales $])
FOR [Month]
IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) AS pvtMonth order by pvtMonth.CardName asc
现在我需要再添加一个名为“Jan Gp”的列名是“X.Gp”。如何更新我的查询。我需要如下结果集
【问题讨论】:
SQL Server,还是别的什么?另外,我觉得这有很多重复;你先搜索了吗? 【参考方案1】:我建议使用条件聚合而不是 pivot
语法。它更加灵活(并且至少同样有效)。你似乎想要这样的东西:
select
cardName,
sum(case when month = 1 then [Total Sales S$] end) [Jan Sales $],
sum(case when month = 1 then [Total Sales SGP] end) [Jan Sales GP],
sum(case when month = 2 then [Total Sales S$] end) [Feb Sales $],
sum(case when month = 2 then [Total Sales SGP] end) [Feb Sales GP],
...
from data
group by cardName
【讨论】:
您知道,“条件聚合”被称为“CROSSTAB”。 @JeffModen 怎么做可以帮忙? @GMB 上面的回答是正确的。它使用 CROSSTAB,它通常比 PIVOT 更快(尤其是对于您要求的两列 Pivots),允许进行更多的自定义,并且可以轻松实现行总计和列总计。以上是关于SQL 查询两个 PIVOT 列组合的主要内容,如果未能解决你的问题,请参考以下文章