SQL 服务器 - 连接前 5 行
SQL Server - Concatenate previous 5 rows
我有 sql 代码,它在分区和排序后创建 column1 中前 5 行的平均值:
CAST (AVG(col1) OVER (Partition by col2 ORDER BY col3 ASC ROWS BETWEEN 5 PRECEDING AND 1 PRECEDING) AS DECIMAL(3,2)) AS col1avg
我想做类似的事情,但不是平均 5 个值,我想创建一个字符串,其中 5 个值用逗号分隔。
我尝试了多种想法但没有成功。任何帮助将不胜感激。
SQL Server 2012+ 中最简单的方法是使用 CONCAT()
和 LAG()
:
select CONCAT(LAG(col1, 1) OVER (PARTITION BY col2 ORDER BY col3), ',',
LAG(col1, 2) OVER (PARTITION BY col2 ORDER BY col3), ',',
LAG(col1, 3) OVER (PARTITION BY col2 ORDER BY col3), ',',
LAG(col1, 4) OVER (PARTITION BY col2 ORDER BY col3), ','
LAG(col1, 5) OVER (PARTITION BY col2 ORDER BY col3)
)
如果您需要处理 NULL
值,这有点棘手。我建议使用空格 trim 并替换:
select REPLACE(RTRIM(CONCAT(LAG(col1, 1, '') OVER (PARTITION BY col2 ORDER BY col3), ' ',
LAG(col1, 2, '') OVER (PARTITION BY col2 ORDER BY col3), ' ',
LAG(col1, 3, '') OVER (PARTITION BY col2 ORDER BY col3), ' ',
LAG(col1, 4, '') OVER (PARTITION BY col2 ORDER BY col3), ' ',
LAG(col1, 5, '') OVER (PARTITION BY col2 ORDER BY col3)
)
), ' ', ','
)
我有 sql 代码,它在分区和排序后创建 column1 中前 5 行的平均值:
CAST (AVG(col1) OVER (Partition by col2 ORDER BY col3 ASC ROWS BETWEEN 5 PRECEDING AND 1 PRECEDING) AS DECIMAL(3,2)) AS col1avg
我想做类似的事情,但不是平均 5 个值,我想创建一个字符串,其中 5 个值用逗号分隔。 我尝试了多种想法但没有成功。任何帮助将不胜感激。
SQL Server 2012+ 中最简单的方法是使用 CONCAT()
和 LAG()
:
select CONCAT(LAG(col1, 1) OVER (PARTITION BY col2 ORDER BY col3), ',',
LAG(col1, 2) OVER (PARTITION BY col2 ORDER BY col3), ',',
LAG(col1, 3) OVER (PARTITION BY col2 ORDER BY col3), ',',
LAG(col1, 4) OVER (PARTITION BY col2 ORDER BY col3), ','
LAG(col1, 5) OVER (PARTITION BY col2 ORDER BY col3)
)
如果您需要处理 NULL
值,这有点棘手。我建议使用空格 trim 并替换:
select REPLACE(RTRIM(CONCAT(LAG(col1, 1, '') OVER (PARTITION BY col2 ORDER BY col3), ' ',
LAG(col1, 2, '') OVER (PARTITION BY col2 ORDER BY col3), ' ',
LAG(col1, 3, '') OVER (PARTITION BY col2 ORDER BY col3), ' ',
LAG(col1, 4, '') OVER (PARTITION BY col2 ORDER BY col3), ' ',
LAG(col1, 5, '') OVER (PARTITION BY col2 ORDER BY col3)
)
), ' ', ','
)