Search code examples
sqlsql-serversql-server-2014

get maximum date and time in duplicate table sql server


i want to ask about how to get sort of maximum date and maximum time when there is a lot of duplicate data.

i am using this query to show the data

/****** Script for SelectTopNRows command from 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

as you can see, the result from this is like this image below. enter image description here

the question is how to get the result like this. where i want to get the minimum ActivitityTimeStart and maximum ActivityTimeEnd in respective date

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

Solution

  • Do you just want a simple 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;