Brain freeze join issue.

  • What's the most elegant way to achieve the following? ...

    CREATE TABLE TabOne

    (db CHAR(1), type INT, size INT)

    INSERT INTO TabOne VALUES ('a', 1, 1)

    INSERT INTO TabOne VALUES ('a', 2, 2)

    INSERT INTO TabOne VALUES ('a', 2, 2)

    INSERT INTO TabOne VALUES ('b', 1, 3)

    INSERT INTO TabOne VALUES ('b', 1, 5)

    INSERT INTO TabOne VALUES ('b', 2, 4)

    INSERT INTO TabOne VALUES ('c', 1, 5)

    INSERT INTO TabOne VALUES ('c', 2, 6)

    INSERT INTO TabOne VALUES ('c', 3, 7)

    SELECT * FROM TabOne

    SELECT db, type, SUM(size) as SumSize

    FROM TabOne

    GROUP BY db, type

    ORDER BY 1,2

    dbtypeSumSize

    a11

    a24

    b18

    b24

    c15

    c26

    c37

    I want to have the following results ...

    db type1 SumSizeType1 type2 SumSizeType2 type3

    a 1 1 2 4 ...

    b ....

    Hope it's clear. Grateful for your time, as ever!

    🙂

  • Looks like you are looking for "Dynamic Pivot":

    http://www.sqlservercentral.com/articles/Crosstab/65048/

    _____________________________________________
    "The only true wisdom is in knowing you know nothing"
    "O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D
    (So many miracle inventions provided by MS to us...)

    How to post your question to get the best and quick help[/url]

  • Perfect. Thanks Eugene.

    SELECT db,

    SUM(CASE WHEN type = 1 THEN size ELSE 0 END) AS [Type1],

    SUM(CASE WHEN type = 2 THEN size ELSE 0 END) AS [Type2],

    SUM(CASE WHEN type = 3 THEN size ELSE 0 END) AS [Type3],

    SUM (size) AS TotalSize

    FROM #TabOne

    GROUP BY db

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply