下午好, 我想知道是否可以根据表中的行数进行查询以生成列
example:
ID COD DIAG
111111111 | Z359 | D
111111112 | Z359 | D
111111112 | Z359 | D
111111113 | Z359 | R
111111113 | Z359 | P
111111113 | Z359 | R
111111114 | Z359 | D
111111114 | Z359 | D
111111114 | Z359 | D
111111115 | Z359 | D
it would be ideal that columns be created according to the number of rows for each id, if not possible it would put a fixed number of columns.
result query
ID | COD1 | DIAG1 | COD2 | DIAG2 | COD3 | DIAG3
111111111 | Z359 | D | | | |
111111112 | Z359 | D | Z359 | D | |
111111113 | Z359 | R | Z359 | P | Z359 | R
111111114 | Z359 | D | Z359 | D | Z359 | D
111111115 | Z359 | D | | | |
对不起我的英语
非常感谢!
答案 0 :(得分:0)
第一个查询遵循answer to the duplicate question的模式,在此包括以进行比较。
no food
breakfast,marmalade
breakfast,coffee
lunch,dessert
dinner
no food
no food
dinner,dessert
但这确实是天真的使用窗口函数,因为它可以通过同时计算其他值来最大化窗口。第一个查询已经在收集并遍历已分区的行以获取行号,但是本质上它通过使用聚合max()函数在下一个查询中收集值来重复该过程两次。
以下查询看起来更长或更复杂,但是它通过在同一过程中收集转换后的值来利用分区数据(即窗口数据)。但是由于窗口函数必须在每一行上运行,因此有必要过滤掉“不完整”的行。我没有对查询进行任何类型的分析,但是我怀疑第二个查询总体上效率更高。
WITH numbered AS (
SELECT row_number() OVER
(PARTITION BY ID ORDER BY COD, DIAG)
AS seq,
t.*
FROM SO58566470 t)
SELECT ID,
max(CASE WHEN seq = 1 THEN COD END) AS COD1,
max(CASE WHEN seq = 1 THEN DIAG END) AS DIAG1,
max(CASE WHEN seq = 2 THEN COD END) AS COD1,
max(CASE WHEN seq = 2 THEN DIAG END) AS DIAG1,
max(CASE WHEN seq = 3 THEN COD END) AS COD3,
max(CASE WHEN seq = 3 THEN DIAG END) AS DIAG3
FROM numbered n
GROUP BY ID;