Pivot query

scottic 21 Reputation points
2022-07-07T17:07:28.74+00:00

I am trying to generate a result set from below data

218686-image.png

desired result set :
218731-image.png

SQL Server Integration Services
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
SQL Server | Other
{count} votes

Answer accepted by question author
  1. Erland Sommarskog 129.1K Reputation points MVP Volunteer Moderator
    2022-07-07T22:03:08.647+00:00

    No, this should not be done in SQL. It's not uncommon to do dynamic pivots in SQL Server, although it is a non-relational operation. But you are taking things one step further by having multiple columns for the same header value.

    Yes, I am sure we can write some ugly dynamic SQL for this, but you are looking for a presentational device, and that belongs in the presentation layer. So have SQL Server return a relational result set, and let Python or whatever do the formatting.

    1 person found this answer helpful.
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Dillon Silzer 60,726 Reputation points Volunteer Moderator
    2022-07-07T19:07:22.303+00:00

    The following steps and code should be able to help you achieve Transposing (PIVOT) the table in Microsoft SQL

    https://www.sqlshack.com/dynamic-pivot-tables-in-sql-server/

    218717-image.png

    --------------------------

    If this answer has helped please don't forget to mark as answer. Have a good day.

    0 comments No comments

  2. LiHong-MSFT 10,061 Reputation points
    2022-07-08T02:56:20.64+00:00

    Hi @scottic
    I don't think it's a good choice to use PIVOT in SQL Sever, cause when you use PIVOT, you need to do some aggregate calculation which is no need in your issue.
    BTW, not sure why you want to get a result table like this, wouldn't it make more sense to have a table like the one below?
    218822-image.png

    Best regards,
    LiHong

    0 comments No comments

  3. scottic 21 Reputation points
    2022-07-08T19:25:32.067+00:00

    I give up doing this in SQL. I am now trying it in Python. Thanks guys for the suggestions

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.