Dynamic pivot query with multiple columns

Lylyy 380 Reputation points
2024-01-30T03:05:51.06+00:00

Trying to write dynamic pivot query referring from this article: Dynamic Pivot Tables in SQL Server However I am not able to pivot multiple columns dynamically. Is there any tutorial or samples?

SQL Server Other
{count} votes

Accepted answer
  1. LiHongMSFT-4306 31,566 Reputation points
    2024-01-30T03:50:11.5833333+00:00

    Hi @Lylyy

    If you want to pivot multiple columns, then it is suggested that you use case when along with aggregate function instead of PIVOT.

    Here is a doc for your reference: T-SQL: Dynamic Pivot on Multiple Columns.

    Also, see this blog: Dynamic PIVOT on multiple columns.

    Best regards, Cosmog Hong

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2024-01-30T22:34:22.09+00:00

    I have some text on dynamic pivot here, including multiple columns and subtotals and grand totals: https://www.sommarskog.se/dynamic_sql.html#pivot

    0 comments No comments

Your answer

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