2017-03-06 36 views
0

我想问如何得到排序的最大日期和最大时间,当有很多重复的数据。得到最大日期和时间在重复表sql server

我使用这个查询来显示数据

/******的脚本SelectTopNRows从SSMS命令******/

SELECT 
     trx.[ActivityDate] 
     ,trx.ActivityTimeStart 
     ,trx.ActivityTimeEnd 
     ,trx.[EmployeeID] 
     ,trx.[ApprovalStatusID] 
     ,mst.[FullName] 
    FROM [KairosManagementSystem].[dbo].[Tbl_Trx_TimeSheet] trx 
    INNER JOIN [dbo].[Tbl_Mst_Employee] mst 
    ON trx.[EmployeeID] = mst.[EmployeeID] 
    where datepart(year,trx.[ActivityDate]) between datepart(year, dateadd(year,-1,getdate())) and datepart(year, getdate()) 
    and 
    trx.[ActivityDate] <= getdate() 
    and 
    trx.EmployeeID = 11460 
order by trx.[ActivityDate] DESC 

,你可以看到,由此产生的结果如下图所示。 enter image description here

问题是如何得到这样的结果。在这里我想获得最低ActivitityTimeStart和最大ActivityTimeEnd在相应的日期

---------------------------------------------------------------------------- 
|ActivityDate | ActivityTimeStart | ActivityTimeEnd | EmployeeID | FullName 
---------------------------------------------------------------------------- 
|2017-02-17 | 07:00:00 00:00:00 | 16:00:00 00:00:00| 11460  | Yohanes 

回答

1

你只想要一个简单的GROUP BY

SELECT trx.[ActivityDate], MIN(trx.ActivityTimeStart), MAX(trx.ActivityTimeEnd), 
     trx.[EmployeeID], mst.[FullName] 
FROM [KairosManagementSystem].[dbo].[Tbl_Trx_TimeSheet] trx INNER JOIN 
    [dbo].[Tbl_Mst_Employee] mst 
    ON trx.[EmployeeID] = mst.[EmployeeID] 
WHERE YEAR(trx.[ActivityDate]) between YEAR(dateadd(year,-1,getdate())) and YEAR(getdate()) and 
     trx.[ActivityDate] <= getdate() and 
     trx.EmployeeID = 11460 
GROUP BY trx.[ActivityDate], trx.[EmployeeID], mst.[FullName] 
ORDER BY trx.[ActivityDate] DESC; 
+0

非常感谢你:),作品像一个魅力 –

相关问题