Home > database >  How to pivot table in sql?
How to pivot table in sql?

Time:02-02

I need to pivot a table, but I am stuck because of reapeated Action values. Goal: extract values from the Action column and use them as the headers for new columns. Then, fill the new table with values from the Val column. In this instance, there is only one group, so you can utilize a window function to capture all groups with ID column. All SN are unique, but other actions can be repeated for the same SN

I have a table:

Val Action ID
SN1844Q SN 94a52150-a24f-11ed
2000 Check_X 94a52150-a24f-11ed
1 Pass 94a52150-a24f-11ed
2022-01-12 23:51:31 DateTime 94a52150-a24f-11ed
up Position 94a52150-a24f-11ed
back Position 94a52150-a24f-11ed
890 Check_X 94a52150-a24f-11ed
SN1845Q SN 28497a86-8e8e-44da
... ... ...

I want to see:

SN Check_X Pass DateTime Position
SN1844Q 2000 1 2022-01-12 23:51:31 up
SN1844Q 890 1 2022-01-12 23:51:31 back
... ... ... ... ...

CodePudding user response:

SELECT SN,
       MAX(CASE WHEN Action = 'Action 1' THEN Val END) AS "Action 1",
       MAX(CASE WHEN Action = 'Action 2' THEN Val END) AS "Action 2",
       MAX(CASE WHEN Action = 'Action 3' THEN Val END) AS "Action 3"
FROM original_table
GROUP BY SN

In this query, the MAX function is used in the CASE statement to aggregate the values from the Val column, while the GROUP BY clause is used to group the results by the SN column. The CASE statement is used to match the values in the Action column and return the corresponding values from the Val column. The result of the query will be a new table with columns for each unique value in the Action column, with the values from the Val column filling in the appropriate cells

CodePudding user response:

You have to use SQL pivot with a dynamic query click here .

  • Related