通过给出“不包含在聚合函数”(SQL-server)来进行自连接和分组

时间:2022-04-22 15:54:36

Good day, Here's what I'm trying to do..

你好,这是我想做的。

ITEM   |   CATEGORY    |    AMOUNT
Sponge         A              29
Sponge         B              32
Sponge         C              33
Sponge         D              34
Rod            A               1
Rod            B               2
Rod            C               3
Rod            D               4

And I wanted the output to look like this:

我希望输出是这样的

ITEM    |   A   |  B   |   C   |   D
Sponge     29      32      33      34
Rod        1       2       3        5

I've been trying all sorts of combinations of GROUP BY but I can't seem to get it to work.

我一直在尝试各种各样的组合,但我似乎无法让它发挥作用。

2 个解决方案

#1


6  

SELECT ITEM
      ,MAX(CASE WHEN CATEGORY ='A' THEN Amount END) AS A
      ,MAX(CASE WHEN CATEGORY ='B' THEN Amount END) AS B
      ,MAX(CASE WHEN CATEGORY ='C' THEN Amount END) AS C
      ,MAX(CASE WHEN CATEGORY ='D' THEN Amount END) AS D
FROM YourTable
GROUP BY ITEM

Or

SELECT *
FROM YourTable
PIVOT (MAX(AMOUNT) FOR CATEGORY IN ([A],[B],[C],[D])) AS Pvt

#2


1  

WITH    q AS
        (
        SELECT  *
        FROM    (
                VALUES
                ('Sponge', 'A', 29),
                ('Sponge', 'B', 32),
                ('Sponge', 'C', 33),
                ('Sponge', 'D', 34),
                ('Rod', 'A', 1),
                ('Rod', 'B', 2),
                ('Rod', 'C', 3),
                ('Rod', 'D', 4)
                ) q (item, category, amount)
        )
SELECT  *
FROM    q
PIVOT   (
        MAX(amount)
        FOR     category IN ([A], [B], [C], [D])
        ) AS qp

#1


6  

SELECT ITEM
      ,MAX(CASE WHEN CATEGORY ='A' THEN Amount END) AS A
      ,MAX(CASE WHEN CATEGORY ='B' THEN Amount END) AS B
      ,MAX(CASE WHEN CATEGORY ='C' THEN Amount END) AS C
      ,MAX(CASE WHEN CATEGORY ='D' THEN Amount END) AS D
FROM YourTable
GROUP BY ITEM

Or

SELECT *
FROM YourTable
PIVOT (MAX(AMOUNT) FOR CATEGORY IN ([A],[B],[C],[D])) AS Pvt

#2


1  

WITH    q AS
        (
        SELECT  *
        FROM    (
                VALUES
                ('Sponge', 'A', 29),
                ('Sponge', 'B', 32),
                ('Sponge', 'C', 33),
                ('Sponge', 'D', 34),
                ('Rod', 'A', 1),
                ('Rod', 'B', 2),
                ('Rod', 'C', 3),
                ('Rod', 'D', 4)
                ) q (item, category, amount)
        )
SELECT  *
FROM    q
PIVOT   (
        MAX(amount)
        FOR     category IN ([A], [B], [C], [D])
        ) AS qp