我的SQL服务器中有以下多对多关系(见下图)。
在大多数情况下,表tblWavelengths中有2行与表tblSensors相关,(在某些情况下只有1行,在极端情况下可能有20行)
我做了以下简单查询以从这3个表中检索数据:
select W.DateTimeID,S.SensorName,S.SensorType,W.Channel,W.PeakNr,W.Wavelength
from tblWavelengths as W
Left Join tblSensorWavelengths as SW on W.tblWavelengthID = SW.WavelengthID
Left Join tblSensors as S on SW.SensorID = S.SensorID
order by W.DateTimeID
运行此查询后,我得到以下结果:
这是我的问题。我想写一个查询,它只过滤那些在给定时刻(DateTimeID)在tblWavelengths表中有两行(两个不同波长)的传感器(SensorName)。所以例如我想要没有结果 77902/001传感器 - 因为它在给定时刻只有一行(一个波长)与tblSensors相关
答案 0 :(得分:10)
您可以使用窗口函数找出每个sensorname / datetimeid组合的波长数:
WITH Data AS
( SELECT W.DateTimeID,
S.SensorName,
S.SensorType,
W.Channel,
W.PeakNr,
W.Wavelength,
[Wcount] = COUNT(*) OVER(PARTITION BY s.SensorName, d.DateTimeID)
from tblWavelengths as W
LEFT JOIN tblSensorWavelengths as SW
ON W.tblWavelengthID = SW.WavelengthID
LEFT JOIN tblSensors as S
ON SW.SensorID = S.SensorID
)
SELECT DateTimeID, SensorName, SensorType, Channel, PeakNr, WaveLength
FROM Data
WHERE Wcount = 2
ORDER BY DateTimeID;
<强>附录强>
作为后来的想法我意识到,对于一个具有相同波长的传感器,您可能有两个结果,这将返回2个记录,但没有两个不同的波长。由于窗口函数不支持使用DISTINCT
,因此替代
WITH Data AS
( SELECT W.DateTimeID,
S.SensorName,
S.SensorType,
W.Channel,
W.PeakNr,
W.Wavelength,
W.tblWaveLengthID
from tblWavelengths as W
LEFT JOIN tblSensorWavelengths as SW
ON W.tblWavelengthID = SW.WavelengthID
LEFT JOIN tblSensors as S
ON SW.SensorID = S.SensorID
)
SELECT d.DateTimeID, d.SensorName, d.SensorType, d.Channel, d.PeakNr, d.WaveLength
FROM Data d
INNER JOIN
( SELECT DateTimeID, SensorName
FROM Data
GROUP BY DateTimeID, SensorName
HAVING COUNT(DISTINCT tblWaveLengthID) = 2
) t
ON t.DateTimeID = d.DateTimeID
AND t.SensorName = d.SensorName
ORDER BY d.DateTimeID;