如果存在其他非空值,则删除Null

时间:2017-11-08 03:56:06

标签: sql-server null

如果特定CaseNumber存在其他非空值,如何删除空值?

以下是原始数据(表1)

CaseNumber |  Date
-----------|-----------
A          | NULL
A          | 08/11/2017
B          | 07/11/2017
B          | 06/11/2017
C          | NULL
C          | NULL
D          | NULL
F          | 05/11/2017
F          | NULL
F          | 04/11/2017
G          | 03/11/2017
G          | NULL

以下是我想要的结果。

CaseNumber |  Date
-----------|-----------
A          | 08/11/2017
B          | 07/11/2017
B          | 06/11/2017
C          | NULL
D          | NULL
F          | 05/11/2017
F          | 04/11/2017
G          | 03/11/2017

我正在使用SQL Server 2012。

2 个答案:

答案 0 :(得分:3)

在类似问题here中回答了这个问题。

Easiest way to eliminate NULLs in SELECT DISTINCT?

在你的情况下:

SELECT DISTINCT * FROM Table1
WHERE Date IS NOT NULL OR CaseNumber IN (
  SELECT CaseNumber FROM Table1
  GROUP BY CaseNumber HAVING MAX(Date) IS NULL)

答案 1 :(得分:1)

您可以选择不同的 CaseNumber 左连接所有日期不为空的记录:

;with not_null as (
  select * from t
  where date is not null
), unique_case as (
  select distinct casenumber 
  from t
)
select unique_case.CaseNumber, not_null.Date from unique_case
left outer join not_null
on unique_case.CaseNumber=not_null.CaseNumber

以下是包含虚假数据的fiddle

相关问题