pivot with group by


  • Hi All,
    I need your assist in a simple query to pivot the below data and group them by docid.

  • tanehome - Thursday, November 15, 2018 2:41 AM


    Hi All,
    I need your assist in a simple query to pivot the below data and group them by docid.

    ;WITH SampleData AS (
     SELECT *
     FROM (VALUES
      ('doc1', 1, 'a'),
      ('doc1', 2, 'b')
     ) d (docid, ver, code)
    )
    SELECT
     docid,
     [1] = MAX(CASE WHEN ver = 1 THEN code END),
     [2] = MAX(CASE WHEN ver = 2 THEN code END)
    FROM SampleData
    GROUP BY docid

    For more info see this article.

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

  • tanehome - Thursday, November 15, 2018 2:41 AM


    Hi All,
    I need your assist in a simple query to pivot the below data and group them by docid.

    Chris's cross tab query is very good. To know that different solution exist try below one


    ;WITH SampleData AS (
    SELECT *
    FROM (VALUES
    ('doc1', 1, 'a'),
    ('doc1', 2, 'b')
    ) d (docid, ver, code)
    )
    select * from
    (SELECT
    *
    FROM SampleData) da
    pivot
    (
    --min(ver) for code in (a,b)
    min(code) for ver in ([1],[2])
    )as dat

    Saravanan

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

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