2015-12-02 85 views
1

我將以下查詢作爲子查詢。我需要每siteid帶回一個記錄,最大數量爲grossinternalarea。麻煩是這不起作用,可能有多個buildingid與最大grossinternalarea相同。我必須包含buildingid,因爲這會在隨後的加入中使用。如果你看看結果列表,你會看到一個siteid重複,行3 & 4. 我怎麼才能返回一個buildingIDs?我不在乎哪一個..每組返回單個記錄,最大值爲

SELECT A.SiteID 
    , a.buildingid 
    , A.BuildYear 
    , A.GrossInternalArea 

    FROM 
    qrySiteBuildingGrossExternalArea A 
    LEFT JOIN qrySiteBuildingGrossExternalArea B 
    ON A.SiteID = B.SiteID AND isnull(A.GrossInternalArea, 0) < isnull(B.GrossInternalArea, 0) 
    WHERE 
    isnull(A.GrossInternalArea, 0) <> 0 
    AND B.GrossInternalArea IS NULL 
    ORDER BY 
    A.SiteID 
    , A.BuildingID 

enter image description here

+0

它是SITEID或buildingID和圖像被切斷。 – Paparazzi

回答

0

嵌入在另外一個子查詢和使用row_number

... 
SELECT * 
FROM (SELECT A.SiteID , 
        a.buildingid , 
        A.BuildYear , 
        A.GrossInternalArea , 
        ROW_NUMBER() OVER (PARTITION BY A.SiteID ORDER BY A.GrossInternalArea DESC) rn 
      FROM  qrySiteBuildingGrossExternalArea A 
        LEFT JOIN qrySiteBuildingGrossExternalArea B ON A.SiteID = B.SiteID 
                   AND ISNULL(A.GrossInternalArea, 
                   0) < ISNULL(B.GrossInternalArea, 
                   0) 
      WHERE  ISNULL(A.GrossInternalArea, 0) <> 0 
        AND B.GrossInternalArea IS NULL 
     ) t 
WHERE rn = 1 
... 
+0

爲了防止其他人使用這個,我在子查詢中取出了該命令。驚人的快速回答喬治! – WelshLady

+0

@WelshLady,是的訂購條款會產生錯誤。我已經刪除了。 –

0

一個簡單的方法來解決,這是不使用該查詢作爲一個子查詢。

而不是做的:

select * 
from table1 
join subquery 
    on ... 

select * 
from table1 t1 
cross apply (
    SELECT 
     top 1 -- need this to filter only one (the biggest one) 
     A.SiteID 
    , a.buildingid 
    , A.BuildYear 
    , A.GrossInternalArea 

    FROM 
     qrySiteBuildingGrossExternalArea A 
    LEFT JOIN qrySiteBuildingGrossExternalArea B 
      ON A.SiteID = B.SiteID AND isnull(A.GrossInternalArea, 0) < isnull(B.GrossInternalArea, 0) 
    WHERE 
     isnull(A.GrossInternalArea, 0) <> 0 
     AND B.GrossInternalArea IS NULL 
     and A.SiteID = t1.SiteID -- you'll need this to link to the outer query 
     and A.BuildingID = t1.BuildingID -- you'll probably need this to link to the outer query 
    order by a.GrossInternalArea desc -- use this to get the max one 
) xx -- give a name here to use in the query