SQL:枢轴后两次列出的列中的值



在查询特定表时,我需要更改结果的结构,使其成为给定年份的所有值都在同一行中,在识别类别的单独列中该值属于。

表看起来像这样(示例数据):

year | category | amount
1991 | A of s   | 56
1992 | A of s   | 55
1993 | A of s   | 40
1994 | A of s   | 51
1995 | A of s   | 45
1991 | Total    | 89
1992 | Total    | 80
1993 | Total    | 80
1994 | Total    | 81
1995 | Total    | 82

我需要的结果是:

year | a_of_s | total
1991 | 56     | 89
1992 | 55     | 80
1993 | 40     | 80
1994 | 51     | 81
1995 | 45     | 82

据我了解,我需要使用 pivot 。但是,我的问题似乎是我不了解枢轴。我试图在类似的问题中调整解决方案的查询,这些问题似乎是答案的一部分,到目前为止,我想出的是:

SELECT year, [A of s], [Total] FROM table
pivot (
    max(amount)
    FOR category in ([A of s], [Total])
) pvt
ORDER BY year

这返回了正确的表结构,但是列A_OF_S和Total中的所有单元格为空,并且每年列出了两次。我缺少什么结果得到我需要的结果?

编辑:修复了评论中指出的错误后,唯一剩下的实际问题是列出了两次年度列中的几年。

可能相关:i在枢轴(最大,sum,min等)任意中使用的聚集函数吗?

我以为您真的不需要旋转桌子,并且结果您需要创建一种替代方法来实现它。

这是我根据您的要求返回的查询。

;With cte as
(
  select year, Amount from tbl
  where category = 'A of s'
)
select 
tbl1.year, tbl2.Amount as A_of_S, tbl1.Amount as Total
from tbl as tbl1
inner join  cte as tbl2 on tbl1.year = tbl2.year
where tbl1.category = 'Total'

这是我在测试日为您创建的SQL小提琴。 -> SQL小提琴

答案要简单得多:

WITH VTE AS(
    SELECT *
    FROM (VALUES (1991,'A of s',56),
                 (1992,'A of s',55),
                 (1993,'A of s',40),
                 (1994,'A of s',51),
                 (1995,'A of s',45),
                 (1991,'Total',89),
                 (1992,'Total',80),
                 (1993,'Total',80),
                 (1994,'Total',81),
                 (1995,'Total',82)) V([year],category, amount))
SELECT [year],
       MAX(CASE category WHEN 'A of s' THEN amount END) AS [A of s],
       MAX(CASE category WHEN 'Total' THEN amount END) AS Total
FROM VTE
GROUP BY [year];

最新更新