代码之家  ›  专栏  ›  技术社区  ›  Yanayaya

如何避免子查询上的聚合错误?[复制品]

  •  0
  • Yanayaya  · 技术社区  · 5 年前

    我有三张桌子:

    • Measurements (MeasureID, Time, Distance, Value)
    • Events(EventID, Time Value)
    • EventValues (EventDataID, EventID, Type, Value)

    我需要获取每一个度量值、最近的事件(在过去)及其关联的事件值数据。

    我现在的问题很难看:

    SELECT 
        M.*,
        (SELECT TOP 1 EV.value FROM [Event] E JOIN EventValues EV ON E.EventID = EV.EventID 
         WHERE M.Time >= E.Time ORDER BY M.Time-E.Time) AS Data,
    FROM [Measure] M 
    ORDER BY M.Distance
    

    它只允许我从 EventValues 桌子(我需要更多)

    有什么办法可以使用连接吗?

    编辑 :我还需要从度量表中选择所有条目,即使它们在第一个事件之前(即,只为联接选择空数据)

    0 回复  |  直到 13 年前
        1
  •  1
  •   GilM    13 年前

    可以使用交叉应用程序。

    SELECT  
        M.*, Data.* 
    FROM [Measure] M 
    CROSS APPLY
         (SELECT TOP 1 EV.* FROM [Event] E JOIN EventValues EV ON E.EventID = EV.EventID  
         WHERE M.Time >= E.Time ORDER BY E.Time DESC) AS Data
    ORDER BY M.Distance 
    
        2
  •  1
  •   amit_g    13 年前

    试试这样的(未测试)

    SELECT * FROM
    (
        SELECT M.*, E.*, EV.EventDataID, EV.Type, EV.Value,
            Rank() over (Partition BY M.MeasureID order by M.Time - E.Time) as Rank
        FROM [Measure] M 
        INNER JOIN [Event] E ON M.Time >= E.Time
        INNER JOIN EventValues EV ON E.EventID = EV.EventID
    ) T
    WHERE Rank = 1
    

    编辑

    SELECT * FROM
    (
        SELECT M.*, E.*, EV.EventDataID, EV.Type, EV.Value,
            Rank() over (Partition BY M.MeasureID order by M.Time - E.Time) as Rank
        FROM [Measure] M 
        LEFT JOIN [Event] E ON M.Time >= E.Time
        LEFT JOIN EventValues EV ON E.EventID = EV.EventID
    ) T
    WHERE Rank = 1