8

我的 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 相关

4

1 回答 1

10

您可以使用窗口函数来找出每个传感器名称/日期时间ID组合的波长数:

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;
于 2013-02-01T10:41:42.390 回答