以最大值返回每组的单个记录

时间:2015-12-02 11:05:23

标签: sql-server group-by max

我有以下查询作为子查询。我需要使用siteidgrossinternalarea张回一条记录。麻烦的是,如果可能有多个buildingid具有相同的最大grossinternalarea,则不起作用。我必须包含buildingid,因为这会在后续联接中使用。如果您查看结果列表,您会看到siteid重复,第3行和第3行。 4。 我怎样才能返回一个buildingID?我不在乎哪一个..

    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

2 个答案:

答案 0 :(得分: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
...

答案 1 :(得分:0)

解决此问题的一种简单方法是不将此查询用作子查询。

而不是:

select *
from table1
join subquery
  on ...

DO

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