开发者

self-join and group by giving "not contained in aggregate function" (SQL-server)

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:

开发者_JAVA技巧
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.


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜