MSSQL:只有GROUP BY中的最后一个条目(带有id)

时间:2010-09-27 14:02:54

标签: sql sql-server group-by

关注/复制computhomas's question,但添加了一些曲折...

我在MSSQL2008中有下表

id | business_key | result | date
1 | 1 | 0 | 9
2 | 1 | 1 | 8
3 | 2 | 1 | 7
4 | 3 | n | 6
5 | 4 | 1 | 5
6 | 4 | 0 | 4

现在我想根据business_key进行分组,返回最新日期的完整条目。 所以我的预期结果是:

id | business_key | result | date
1 | 1 | 0 | 9
3 | 2 | 1 | 7
4 | 3 | n | 6
5 | 4 | 1 | 5

我还打赌有一种方法可以实现这一点,我现在无法找到/看到/想到它。

编辑:对不起,我实际上是从原来的问题中做了一些其他事情。我觉得编辑这可能比接受解决方案和提出另一个问题更好。我最初的问题是我没有按ID过滤。

5 个答案:

答案 0 :(得分:15)

SELECT t.*
FROM
(
    SELECT *, ROW_NUMBER() OVER
              (
                  PARTITION BY [business_key]
                  ORDER BY [date] DESC
              ) AS [RowNum]
    FROM yourTable
) AS t
WHERE t.[RowNum] = 1

答案 1 :(得分:3)

SELECT 
       *
FROM 
       mytable 
WHERE 
       ID IN (SELECT MAX(ID) FROM mytable GROUP BY business_key)

答案 2 :(得分:2)

如何(在问题更改后编辑):

with latestdate as (
  select business_key, maxdate=max(date)
  from the_table
  group by business_key
), latest as (
  select ID = max(id)
  from the_table
    inner join latestdate
     on the_table.business_key=latestdate.business_key
       and the_table.date=latestdate.maxdate
  group by the_table.business_key
)
select the_table.*
from the_table
  inner join latest
    on latest.id=the_table.id

答案 3 :(得分:2)

SELECT 
     MAX(T1.id) AS [id],
     T1.business_key, 
     T1.result 
FROM 
     dbo.My_Table T1 
LEFT OUTER JOIN dbo.My_Table T2 ON 
     T2.business_key = T1.business_key AND 
     T2.id > T1.id 
WHERE 
     T2.id IS NULL 
GROUP BY T1.business_key, 
     T1.result 
ORDER BY MAX(T1.id)

根据说明进行编辑

SELECT M1.*
FROM My_Table M1
INNER JOIN 
(
    SELECT [business_key], MAX([date]) as MaxDate
    FROM My_Table 
    GROUP BY [business_key]
) M2 ON M1.business_key = M2.business_key AND M1.[date] = M2.MaxDate
ORDER BY M1.[id]

答案 4 :(得分:2)

假设business_key和amp;的结合日期是独一无二的......

工作示例(第3次是魅力):

declare @src as table(id int, business_key int,result int,[date] int)
insert into @src
SELECT 1,1,0,9
UNION SELECT 2,1,1,8
UNION SELECT 3,2,1,7
UNION SELECT 4,3,1,6
UNION SELECT 5,4,1,5
UNION SELECT 6,4,0,4

;with bkdate(business_key,[date])
AS
(
    select business_key,MAX([date])
    from @src 
    group by business_key
)
select src.* from @src src 
inner join bkdate
ON src.[date] = bkdate.date
and src.business_key = bkdate.business_key
order by id