为每个主标识符选择一行,其中每个id有多行,包含null和非null值

时间:2017-09-20 18:03:23

标签: sql tsql

我有一个查询行,返回结果,如下所示:

+--------------+------+-------+-------+------+------+--------+--------+--------+------+------+------+------+------+------+
|ID            | LC1  | IL1   |  IL2  | WT1  |  WT2 |   HN1  |  HN2   |   St   | P/H  | PN1  |  PN2 |  C1  |  C2  |  PW  |
+--------------+------+-------+-------+------+------+--------+--------+--------+------+------+------+------+------+------+
|NDP-5-SC-0014 | NULL | NULL  | 24.52 | NULL | 12.7 |  NULL  | 521502 |  NULL  | NULL | NULL | 509  | FBE  | NULL | NULL |
|NDP-5-SC-0014 | NULL | 18.07 | 24.52 | 12.7 | 12.7 | 402772 | 521502 | 341615 | NULL | 380  | 509  | FBE  | FBE  | NULL |
|NDP-5-SC-0014 | NULL | 18.08 |  NULL | 12.7 | NULL | 402772 |  NULL  |  NULL  | NULL | 380  | NULL | NULL | FBE  | NULL |

我想选择它以便显示为:

+--------------+------+-------+-------+------+------+--------+--------+--------+------+------+------+------+------+------+    
|ID            | LC1  | IL1   |  IL2  | WT1  |  WT2 |   HN1  |  HN2   |   St   | P/H  | PN1  |  PN2 |  C1  |  C2  |  PW  |
+--------------+------+-------+-------+------+------+--------+--------+--------+------+------+------+------+------+------+
|NDP-5-SC-0014 | NULL | 18.07 | 24.52 | 12.7 | 12.7 | 402772 | 521502 | 341615 | NULL | 380  | 509  | FBE  | FBE  | NULL |

我想为每个ID选择一行,并为其余字段仅抓取一个非空值。

1 个答案:

答案 0 :(得分:3)

概念上..您希望在除MAX()之外的所有列上使用MIN()ID(最适合您的需求)等汇总,GROUP BY SELECT ID, MAX(LC1), MAX(IL1), rest of columns FROM (Your Query) A --May or may not need to put your query in a derived table GROUP BY ID }。

如果没有看到你的查询,就不可能给你正确的回复,但它会是这样的:

{{1}}