如何只获得表连接的第一个结果?

时间:2013-02-14 18:24:02

标签: sql sql-server

我有一个问题:

SELECT  

    Segment_ID = Segment_ID.Segment_ID,
    Sprav_093.Name as Road_Wear

FROM dbo.Road
LEFT JOIN Segment_ID  ON Road.Road_ID = Segment_ID.Road_ID
LEFT JOIN Driveway_Pavement ON Segment_ID.Segment_ID = Driveway_Pavement.Segment_ID
LEFT JOIN Sprav_093 ON Driveway_Pavement.Kod_Spr093 = Sprav_093.Kod_Spr

工作正常。表Segment_ID中有多个行具有相同的Driveway_Pavement。所以我想要获得这些行中的第一行。我该怎么办?

3 个答案:

答案 0 :(得分:5)

假设您想为每个段ID返回一行,请执行此操作

;WITh CTE AS (
SELECT  

    Segment_ID = Segment_ID.Segment_ID,
    Sprav_093.Name as Road_Wear,
    CASE WHEN Sprav_093.Name IS NOT NULL THEN 
    ROW_NUMBER() OVER (PARTITION BY Segment_ID.Segment_ID 
                       ORDER BY Sprav_093.Name//or date column) 
    ELSE 1 END rn

FROM dbo.Road
LEFT JOIN Segment_ID  ON Road.Road_ID = Segment_ID.Road_ID
LEFT JOIN Driveway_Pavement ON Segment_ID.Segment_ID = Driveway_Pavement.Segment_ID
LEFT JOIN Sprav_093 ON Driveway_Pavement.Kod_Spr093 = Sprav_093.Kod_Spr
)
SELECT * FROM CTE WHERE RN = 1

答案 1 :(得分:0)

尝试将MAX函数应用于两个选定的字段

答案 2 :(得分:0)

这应该有效:

SELECT  

    Segment_ID = Segment_ID.Segment_ID,
    Sprav_093.Name as Road_Wear

FROM dbo.Road
OUTER APPLY (
    SELECT TOP 1 Segment_ID.Segment_ID
    FROM Segment_ID
    WHERE Segment_ID.Road_ID = Road.Road_ID
) Segment_ID  
LEFT JOIN Driveway_Pavement ON Segment_ID.Segment_ID = Driveway_Pavement.Segment_ID
LEFT JOIN Sprav_093 ON Driveway_Pavement.Kod_Spr093 = Sprav_093.Kod_Spr

如果您想要特定的“第一”行,可以向ORDER BY内的SELECT添加OUTER APPLY