Monday, 15 August 2011

sql server - How Get start Hour and End Hour from a datetime field SQLServer -



sql server - How Get start Hour and End Hour from a datetime field SQLServer -

i have 2 tables in sql server 2008. source table have 2 fields: userid , date (datetime). target table have 4 fields: - userid, day, starthour , endhour -. need find repeated days extract 2 fields ( starthour end endhour) in target table without repeat day.

source table:

class="lang-none prettyprint-override">userid thedate ------ ----------------------- 0001 2014-07-23 08:18:02.000 0001 2014-07-23 16:04:02.000 0002 2014-07-23 08:00:00.000 0003 2014-07-23 09:00:00.000

target table:

class="lang-none prettyprint-override">userid thedate starthour endhour ------ ---------- ---------------- ---------------- 0001 2014-07-23 08:18:02 16:04:02 0002 2014-07-23 08:00:00 null 0003 2014-07-23 09:00:00 null

select userid ,dateonly ,convert(time, min(thedate)) starthour ,case when max(thedate) = min(thedate) null else convert(time, max(thedate)) end endhour #t cross apply ( select convert(date, thedate) dateonly ) ca1 grouping userid ,dateonly

sql-server sql-server-2008 datetime

No comments:

Post a Comment