Question

Could you help me out with the following query?

My goal:

For each day and for each employee select minimum datetime and the maximum datetime and get the time difference in minutes

My query :

SELECT 
   PersonalId, Name, LastName, 
   Min(TmsPrick) as MinDatetime, 
   Max(TmsPrick) as MaxDatetime, 
   DATEDIFF(mi, MIN(TmsPrick), MAX(TmsPrick)) AS Expr1
FROM 
   prickTable
GROUP BY 
   DATEPART(dy, TmsPrick), PersonalId, name, lastname, TmsPrick
ORDER BY 
   PersonalId, TmsPrick

Note: DATEPART(dy, TmsPrick) = Day of year

My expected output

  PersonalId | Name      | LastName   | MinDatetime       | MaxDatetime        | Expr1
  ------------------------------------------------------------------------------------
   000001    | A         | AC         |2014-01-05 07:12:00|2014-01-05 16:00:00 | 528
   000001    | A         | AC         |2014-01-06 07:08:00|2014-01-05 16:00:00 | 532
   000001    | A         | AC         |2014-01-07 07:11:00|2014-01-07 16:00:00 | 529
   000002    | B         | BD         |2014-01-05 07:11:00|2014-01-05 16:00:00 | 529

The output I'm getting:

  PersonalId | Name      | LastName   | MinDatetime       | MaxDatetime        | Expr1
  ------------------------------------------------------------------------------------
   000001    | A         | AC         |2014-01-05 07:12:00|2014-01-05 16:00:00 | 1053168
   000001    | A         | AC         |2014-01-06 07:08:00|2014-01-05 16:00:00 | 532
   000001    | A         | AC         |2014-01-07 07:11:00|2014-01-07 16:00:00 | 529
   000002    | B         | BD         |2014-01-05 07:11:00|2014-01-05 16:00:00 | 1053169

Any idea why my output shows such differences?

Thanks

Note: The values in Tmsprick may vary from several a day to 2 in a week. The table contains values from over 3 years.

Was it helpful?

Solution 2

I suspect that the query that you want is:

SELECT PersonalId, Name, LastName,
       Min(TmsPrick) as Mintime, Max(TmsPrick) as Maxtime, 
       DATEDIFF(mi, MIN(TmsPrick), MAX(TmsPrick)) AS Expr1
FROM prickTable
GROUP BY PersonalId, name, lastname, cast(TmsPrick as date)
ORDER BY PersonalId, max(TmsPrick);

This will give the the "elapsed" time on each day, because the first and last "tmsprick".

OTHER TIPS

Well, without seeing the source data it's hard to know for sure, but you're using different date columns in the MAX/MIN and DATEDIFF:

SELECT 
    PersonalId, 
    Name, 
    LastName, 
    Min(TmsPrick) as MinDatetime, 
    Max(TmsPrick) as MaxDatetime , 
    DATEDIFF(mi, MIN(tijdstip), MAX(tijdstip)) AS Expr1
                     ^-- should be TmsPrick?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top