如何从每组获得前1行? (T-SQL)

时间:2016-10-24 15:38:00

标签: sql sql-server tsql

我有一个看起来像这样的表:

ID    Month    Year
 1      3       2016
 1      5       2016
 1      2       2016
 2      3       2016
 2      1       2015
 2      NULL    NULL
 3      NULL    NULL
etc...

我希望每个id选择1行,最大年份然后是月份,如果没有其他选择则选择NULL,这样结果如下:

ID    Month    Year
1      5       2016
2      3       2016
3      NULL    NULL

以下是我当前的查询:

SELECT distinct
LogTable.CaseID,
Monthlies.Month,
Monthlies.Year
FROM [LogTable]
LEFT JOIN CTable
on LogTable.SerialNum = CTable.SERIAL_NUM
LEFT JOIN 
tCaseStatus AS CaseStatus ON CaseStatus.CaseGUID = LogTable.CaseGUID LEFT JOIN
tReferredBy AS ReferredBy ON ReferredBy.ReferredByGUID =   LogTable.ReferredByGUID LEFT JOIN
placements AS Placement ON Placement.LogGUID = LogTable.LogGUID LEFT JOIN
PlacementMonth AS Monthlies ON Monthlies.PlacementRowGUID = Placement.PlacementRowGUID LEFT JOIN
tRC AS RC ON RC.RCGUID = LogTable.RCGUID LEFT JOIN
VendorH ON VendorH.LogGUID = LogTable.LogGUID LEFT JOIN
tVendor AS Vendor ON Vendor.VendorGUID = VendorH.VendorGUID 
where CaseStatus.Name = 'Active'
order by Monthlies.Year DESC , Monthlies.Month desc

我已经尝试在表上进行外部应用,从月份和年份开始选择desc月份和年份在外部应用中的第一行,但我得到多行为一些ID。

3 个答案:

答案 0 :(得分:1)

可以使用ROW_NUMBER

处理此类请求
select * from 
(
select row_number() over(partition by ID order by [year] desc,[month] desc) as rn,*
From yourresult
) A
Where RN = 1

答案 1 :(得分:1)

with CTE as
(
select ID, Month, Year, row_number() over(partition by ID order by Year desc, Month desc) as ROW_ORD
from Table1
)
select ID, Month, Year
from CTE
where ROW_ORD = 1

答案 2 :(得分:1)

首先,如果可能,我会避免使用SQL中的关键字列名,即月份和年份。您可以在使用后实现目标:

<强> ROW_NUMBER

  

返回结果集分区中行的序号,从1开始,每个分区的第一行。

Runnable样本:

<a href="http://www.newlink.com/anypost.html">LINK</a>

产地:

CREATE TABLE #LogTable
    (
      [ID] INT ,
      [Month] INT ,
      [Year] INT
    );

INSERT  INTO #LogTable
        ( [ID], [Month], [Year] )
VALUES  ( 1, 3, 2016 ),
        ( 1, 5, 2016 ),
        ( 1, 2, 2016 ),
        ( 2, 3, 2016 ),
        ( 2, 1, 2015 ),
        ( 2, NULL, NULL ),
        ( 3, NULL, NULL );

SELECT  t.ID ,
        t.Month ,
        t.Year
FROM    ( SELECT    ID ,
                    [Month] ,
                    [Year] ,
                    ROW_NUMBER() OVER ( PARTITION BY ID ORDER BY [Year] DESC, [Month] DESC ) row
          FROM      #LogTable
        ) t
WHERE   t.row = 1

DROP TABLE  #LogTable