SQL:如何从分组表中获取每组中的第一行

时间:2016-11-29 10:13:16

标签: sql-server

我有下表

CREATE TABLE [dbo].[Table_1](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nchar](10) NULL,
    [DateOf] [nvarchar](20) NULL
) ON [PRIMARY]

和日期:

ID|Name|DateOf
1|A|2016-11-29 00:01:00
2|A|2016-11-29 00:02:00
3|A|2016-11-29 00:03:00
4|B|2016-11-29 00:01:00
5|B|2016-11-29 00:02:00

如果我喜欢

select name, COUNT(name) from Table_1 group by Name 

我有

A|3
B|2

那么,如何获得像之前一样的结果,只从每个组中取出一行并进行排序?

A|3|2016-11-29 00:01:00
B|2|2016-11-29 00:01:00

其中最后一列将按日期时间排序(现在是nvarchar)

3 个答案:

答案 0 :(得分:1)

您可以使用CTE和排名函数PARTITION BY

            WITH CTE AS
            (          select name, dateof,
                       rn = row_number() over (partition by NAME order by dateof desc)
                       from Table_1 
            )
            SELECT name, dateof  FROM CTE WHERE RN = 1

            select * from (
            select name, dateof, ROW_NUMBER() over(partition by NAME order by dateof desc) as rnk 
            from Table_1 
             ) a where rnk=1

答案 1 :(得分:1)

您可以使用CROSS APPLY

select t1.name, t1.[Count], t2.MinDate
from (
    select name, count(*) as [Count]
    from Table_1
    group by name
) AS t1
cross apply (
    select min(DateOf) as MinDate
    from Table_1 t2
    where t1.Name = t2.Name
) as t2

如果您想获得除行中最小日期之外的其他数据,您可以修改子选择:

select t1.name, t1.[Count], t2.MinDate, t2.ID
from (
    select name, count(*) as [Count]
    from Table_1
    group by name
) AS t1
cross apply (
    select top 1 DateOf as MinDate, ID
    from Table_1 t2
    where t1.Name = t2.Name
    order by DateOf
) as t2

答案 2 :(得分:0)

SELECT T1.Name,A.[COUNT],MIN(DateOf)
FROM Your_table_Name T1
JOIN 
(
 SELECT COUNT(*) [COUNT],T2.Name [Name]
 FROM Your_table_Name T2
 GROUP BY T2.Name
 )A ON A.Name = T1.Name
GROUP BY T1.Name,A.[COUNT]