简单查询以获取组结果

时间:2009-09-09 04:02:30

标签: c# sql

如何才能从以下示例中获得唯一的部门?

Dept Id                                       Created Date 
06013cd7-2224-4220-b048-a54bbd1ff403          2009-09-08 17:36:11.293
06013cd7-2224-4220-b048-a54bbd1ff403          2009-09-08 17:41:54.857
5e29bd98-04ba-452d-bfcd-caa63ab9018b          2009-09-08 17:20:45.373

我试过这个

select top 10 deptid, 
    (Select convert(varchar,createddate,101)) 
from depts 
where [status]='Y' 
group by deptid,convert(varchar,createddate,101)

但显示所有结果。我想要这个:

Dept Id                                       Created Date 
06013cd7-2224-4220-b048-a54bbd1ff403          2009-09-08 
5e29bd98-04ba-452d-bfcd-caa63ab9018b          2009-09-08 

你能帮我写这个查询吗

谢谢

2 个答案:

答案 0 :(得分:2)

SELECT deptid, MAX(createdate) FROM depts WHERE [status] = 'Y' GROUP BY deptid

答案 1 :(得分:2)

您要返回所有行,因为您在分组中包含了日期。尝试:

select deptid, Max(convert(varchar,createddate,101)) AS MaxDate
from depts 
where [status]='Y' 
group by deptid