您需要County、Site、'Site Number, andDate(month), and then you wantIncidentandPriority` 的所有唯一组合的列表(如果存在)。
这是一个两步的问题。首先,生成您的唯一值列表。那是带有GROUP BY 的内部子查询。
然后将LEFT JOIN 返回基表,但仅限于存在Incident 的地方。这是ON 子句中的最后一个JOIN 条件。
结果集将仅显示它存在的 Incident 数据(摆脱您想要删除的空记录),但将为每个没有任何事件的唯一组合创建一个空记录。 COALESCE 声明只是为了使结果更漂亮。
数据设置:
DECLARE @t TABLE
(
County VARCHAR(10) NOT NULL
,Site VARCHAR(10) NOT NULL
,SiteName VARCHAR(10) NOT NULL
,Date VARCHAR(6) NOT NULL
,Incident VARCHAR(5) NULL
,Priority CHAR(2) NULL
);
INSERT @t
(
County
,Site
,SiteName
,Date
,Incident
,Priority
)
VALUES
('C1', 'S1', 'Sn1', 'Jan-19', 'INC3', '')
,('C1', 'S1', 'Sn1', 'Jan-19', '', '')
,('C1', 'S1', 'Sn1', 'Feb-19', 'INC2', '')
,('C1', 'S1', 'Sn1', 'Feb-19', 'INC1', '')
,('C1', 'S1', 'Sn1', 'Feb-19', '', '')
,('C1', 'S2', 'Sn2', 'Jan-19', '', '')
,('C1', 'S2', 'Sn2', 'Feb-19', '', '');
查询:
SELECT
list.County
,list.Site
,list.SiteName
,list.Date
,COALESCE(t1.Incident, '') AS Incident
,COALESCE(t1.Priority, '') AS Priority
FROM
(
SELECT
t.County
,t.Site
,t.SiteName
,t.Date
FROM
@t AS t
GROUP BY
t.County
,t.Site
,t.SiteName
,t.Date
) AS list
LEFT JOIN
@t AS t1
ON
t1.County = list.County
AND t1.Site = list.Site
AND t1.SiteName = list.SiteName
AND t1.Date = list.Date
AND t1.Incident <> '';
结果:
+--------+------+----------+--------+----------+----------+
| County | Site | SiteName | Date | Incident | Priority |
+--------+------+----------+--------+----------+----------+
| C1 | S1 | Sn1 | Feb-19 | INC2 | |
| C1 | S1 | Sn1 | Feb-19 | INC1 | |
| C1 | S1 | Sn1 | Jan-19 | INC3 | |
| C1 | S2 | Sn2 | Feb-19 | | |
| C1 | S2 | Sn2 | Jan-19 | | |
+--------+------+----------+--------+----------+----------+