How can i add MULTIPLE pivot tables in same table?

kkmyghty 41 Reputation points
2022-11-04T12:37:40.62+00:00

![257265-image.png]2

I want my pivot tables to be shown side by side in select query. i currently have 4 pivot tables coming from two tables each.

AND so on..... till jun
I want my output to be like this in sql.
Please help as am new in learning sql, Please suggest me a way to execute my pivot tables all together like a table.
I have tried UNION, MULtiple SELECT, ALIAS and JOINS but no desired results.
help is needed

Azure SQL Database
Developer technologies Transact-SQL
SQL Server Other
{count} votes

Accepted answer
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2022-11-04T22:36:42.06+00:00

    If you are new to SQL, maybe you should let this lie for a year or so. This certainly falls under the advanced category.

    A general comment: a pivoting operation is a presentational device and it is a non-relational operation. That is, relational databases are not designed primarily to perform this sort of operation. Least of all if you want columns to be dynamic.

    In many cases, it is better to perform the pivoting operation in the presentation layer. As I said, it is a presentational device. And there are good pivoting capabilities in Excel. Not that I have used them extensively, but I know they are there. Actually, I think you can use the Get Data option to run your query, and will take you to the PowerPivot component.

    If you still want to do this in SQL, I would recommend that you compose an example with CREATE TABLE for your table(s) and INSERT statements with sample data and you illustrate the desired result from that data. This makes it easy to copy and paste into a query window to develop a tested query. We cannot copy from images.


1 additional answer

Sort by: Most helpful
  1. LiHongMSFT-4306 31,566 Reputation points
    2022-11-07T02:24:49.477+00:00

    Hi @kkmyghty
    I didn't find the group field in your four pivot tables. Because when you perform a PIVOT operation, it is always accompanied by aggregation operations, so grouping columns are necessary.
    You can modify your pivot query to display one more Group column, say: 'xxx_id', so that you can join these four tables on the 'xxx_id' field.

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

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.