Question

My table:

  id    user    area    login         colour
  ------------------------------------------
  1     2       7      2014-01-05     red
  2     1       7      2014-01-03     green
  3     3       7      2014-01-08     red
  4     2       7      2014-01-22     green
  5     3       7      2014-01-15     amber
  6     1       7      2014-01-12     green
  7     3       7      2014-01-23     red
  8     4       7      2014-01-05     red
  9     3       7      2014-01-12     green
 10     4       7      2014-01-28     amber
 11     1       4      2014-01-06     amber

from a list of ONLY each users LAST login (ie MAX(login)) I need a count of those logins from area 7 with the colour green

From the given table, ids 4, 6 and 9 have the latest login date for area 7 and colour green so I would want my query to return their count which is 3.

scratchy head time.

Was it helpful?

Solution

If it's for SQL-Server, you can use windows aggregate functions:

; WITH cte AS
  ( SELECT login, area, colour, 
           maxlogin = MAX(login) OVER (PARTITION BY [user]) 
    FROM dbo.logins
  )
SELECT COUNT(*) AS cnt
FROM cte
WHERE maxlogin = login
  AND area = 7
  AND colour = 'green' ;

Tested at SQL-Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top