title: SQL first and last timestamp per day per user
body: <p>I have a table with a userId and timestamp. For every user, I'd like to get for each day the first and the last timestamp. I'm using SQL Server.
  How it looks like:</p>
  
  <pre><code>|User|         Date        |
  ----------------------------
  | 1  | 2015-01-08 07:31:40 |
  | 1  | 2015-01-08 18:35:40 |
  | 1  | 2015-01-08 22:31:40 |
  | 1  | 2015-01-09 05:35:40 | 
  | 1  | 2015-01-09 06:31:40 |
  | 1  | 2015-01-09 07:35:40 | 
  | 1  | 2015-01-09 12:38:40 | 
  | 1  | 2015-01-09 23:38:40 |    
  | 2  | 2015-01-08 05:55:40 |
  | 2  | 2015-01-08 10:48:40 |
  | 2  | 2015-01-08 15:38:40 |
  | 2  | 2015-01-08 21:50:40 |
  | 2  | 2015-01-09 10:38:40 |
  | 2  | 2015-01-09 14:33:40 |
  | 2  | 2015-01-09 15:38:40 |
  | 2  | 2015-01-09 17:38:40 |
  | 2  | 2015-01-09 19:55:40 |
  </code></pre>
  
  <p>The output I need:</p>
  
  <pre><code>|User|         Date        |
  ----------------------------
  | 1  | 2015-01-08 07:31:40 |
  | 1  | 2015-01-08 22:31:40 |
  | 1  | 2015-01-09 05:35:40 |
  | 1  | 2015-01-09 23:38:40 |
  | 2  | 2015-01-08 05:55:40 |
  | 2  | 2015-01-08 21:50:40 |
  | 2  | 2015-01-09 10:38:40 |
  | 2  | 2015-01-09 19:55:40 |
  </code></pre>
  
  <p>So far it works for only one username:</p>
  
  <pre><code>SELECT 
      User, 
      Date, 
      min(Date) OVER(PARTITION BY Datepart(dy,Date)) as first, 
      max(Date) OVER(PARTITION BY Datepart(dy,Date)) as last
  FROM 
      Tablename
  WHERE 
      User = UserId
  </code></pre>