带有MAX和GUID的SQL Group By

时间:2013-09-03 09:22:50

标签: sql sql-server-2008 group-by

我有这张桌子:

ID                                   Version    IdRoot
887063C3-E1E5-4E76-9EE6-A08300C1DE2E    1       887063C3-E1E5-4E76-9EE6-A08300C1DE2E
ED482E87-D36C-4E50-A6E7-A08300C1DE3C    2       887063C3-E1E5-4E76-9EE6-A08300C1DE2E`
735604E4-25FD-4575-BD88-A08300C1DE41    1       735604E4-25FD-4575-BD88-A08300C1DE41
DA08E433-111D-4C25-9A23-A08300C1DE46    2       735604E4-25FD-4575-BD88-A08300C1DE41
3C0CEED7-0F3A-47C3-90E8-A08300C1DE4A    3       735604E4-25FD-4575-BD88-A08300C1DE41

如何获得仅显示最大版本的SQL?

ID                                   Version    IdRoot
ED482E87-D36C-4E50-A6E7-A08300C1DE3C    2       887063C3-E1E5-4E76-9EE6-A08300C1DE2E
3C0CEED7-0F3A-47C3-90E8-A08300C1DE4A    3       735604E4-25FD-4575-BD88-A08300C1DE41

我运行了这个sql: SELECT ID,MAX([version])as maxversione,idroot FROM Table GROUP BY IdRoot

但SQL管理返回错误:ID必须聚合或插入到组中。

如果我在Group By中插入ID,则sql不会返回正确的数据。

我是SQL 2008。

感谢。

3 个答案:

答案 0 :(得分:1)

像这样使用ranking function ROW_NUMBER()

WITH CTE
AS
(
   SELECT *,
     ROW_NUMBER() OVER(PARTITION BY IdRoot 
                       ORDER BY version DESC) AS RN
   FROM table1
)
SELECT ID, version, IdRoot
FROM  CTE
WHERE RN = 1;

这会给你:

|                                   ID | VERSION |                               IDROOT |
|--------------------------------------|---------|--------------------------------------|
| 3C0CEED7-0F3A-47C3-90E8-A08300C1DE4A |       3 | 735604E4-25FD-4575-BD88-A08300C1DE41 |
| ED482E87-D36C-4E50-A6E7-A08300C1DE3C |       2 | 887063C3-E1E5-4E76-9EE6-A08300C1DE2E |

答案 1 :(得分:0)

可以使用Mahmoud Gamal answer中的窗口函数来执行此操作,但还有其他解决方案:

select
    t.*
from (select distinct IdRoot from Table1) as r
    outer apply (
        select top 1 t.*
        from Table1 as t
        where t.IdRoot = r.IdRoot
        order by [Version] desc
    ) as t

=> sql fiddle demo

或类似的东西:

select
    r.*
from Table1 as r
where
    exists (
        select *
        from Table1 as t
        where t.IdRoot = r.IdRoot
        having max([Version]) = r.[Version]
    )

=> sql fiddle demo

答案 2 :(得分:0)

 SELECT IDRoot, MAX(version) as maxversione,
 (Select ID From Table Where IdRoot = TB.IdRoot And Version = Max(TB.Version)) as ID
 FROM Table TB GROUP BY IdRoot

您可以单独选择ID,如上述查询中所述。