简体   繁体   English

根据ID合并SQL表的非空列的方法

[英]Way to merge non-null columns of a SQL table based on an ID

I have a scenario where I need to have all the non-null valued columns of a SQL table to be merged in a way that the output all all the fields populated with the last non-null value.我有一个场景,我需要合并 SQL 表的所有非空值列,以便 output 所有字段都填充最后一个非空值。

Input ->输入 -> 在此处输入图像描述

Output -> Output -> 在此处输入图像描述

Aggregate by ID and select the MAX value of each column:ID和 select 聚合每列的MAX值:

SELECT ID, MAX(ColA) AS ColA, MAX(ColB) AS ColB, MAX(ColC) AS ColC
FROM yourTable
GROUP BY ID;

Edit: For a bit column in SQL Server, you may cast to integer before taking the max:编辑:对于 SQL 服务器中的位列,您可以在取最大值之前转换为 integer:

SELECT
    ID,
    MAX(CAST(ColA AS int)) AS ColA,
    MAX(CAST(ColB AS int)) AS ColB,
    MAX(CAST(ColC AS int)) AS ColC
FROM yourTable
GROUP BY ID;

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

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