简体   繁体   English

如何将sql中的pivot表?

[英]How to pivot table in sql?

I need to pivot a table, but I am stuck because of reapeated Action values.我需要 pivot 一张表,但由于重复的Action值,我被卡住了。 Goal: extract values from the Action column and use them as the headers for new columns.目标:从Action列中提取值并将它们用作新列的标题。 Then, fill the new table with values from the Val column.然后,用Val列中的值填充新表。 In this instance, there is only one group, so you can utilize a window function to capture all groups with ID column.在本例中,只有一个组,因此您可以使用 window function 来捕获所有具有 ID 列的组。 All SN are unique, but other actions can be repeated for the same SN所有 SN 都是唯一的,但可以对同一个 SN 重复其他操作

I have a table:我有一张桌子:

Val瓦尔 Action行动 ID ID
SN1844Q SN1844Q SN序列号 94a52150-a24f-11ed 94a52150-a24f-11ed
2000 2000 Check_X检查_X 94a52150-a24f-11ed 94a52150-a24f-11ed
1 1个 Pass经过 94a52150-a24f-11ed 94a52150-a24f-11ed
2022-01-12 23:51:31 2022-01-12 23:51:31 DateTime约会时间 94a52150-a24f-11ed 94a52150-a24f-11ed
up向上 Position Position 94a52150-a24f-11ed 94a52150-a24f-11ed
back后退 Position Position 94a52150-a24f-11ed 94a52150-a24f-11ed
890 890 Check_X检查_X 94a52150-a24f-11ed 94a52150-a24f-11ed
SN1845Q SN1845Q SN序列号 28497a86-8e8e-44da 28497a86-8e8e-44da
... ... ... ... ... ...

I want to see:我想看看:

SN序列号 Check_X检查_X Pass经过 DateTime约会时间 Position Position
SN1844Q SN1844Q 2000 2000 1 1个 2022-01-12 23:51:31 2022-01-12 23:51:31 up向上
SN1844Q SN1844Q 890 890 1 1个 2022-01-12 23:51:31 2022-01-12 23:51:31 back后退
... ... ... ... ... ... ... ... ... ...

You have to use SQL pivot with a dynamic query click here .您必须通过动态查询使用 SQL pivot单击此处

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.在此查询中,MAX function 在 CASE 语句中用于聚合来自 Val 列的值,而 GROUP BY 子句用于按 SN 列对结果进行分组。 The CASE statement is used to match the values in the Action column and return the corresponding values from the Val column. CASE 语句用于匹配 Action 列中的值,并从 Val 列返回相应的值。 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查询的结果将是一个新表,其中包含 Action 列中每个唯一值的列,Val 列中的值填充在适当的单元格中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM