-1

It's been a while since I wrote "complex" queries in SQL...

I have a table Attendance with columns

BranchID (int)
SignDate (DateTime) 
EmployeeID (nvarchar)

Each Branch has tens of employees.

What I need is a list the earliest SignDate for each branch per day and EmployeeID who signed.

I tried several ways, but no luck...

I'm using SQL Server.

Thanks.

Dale K
  • 25,246
  • 15
  • 42
  • 71
RoyM
  • 13
  • 4
  • 2
    https://stackoverflow.com/help/minimal-reproducible-example – Aaron Bertrand Aug 31 '21 at 20:02
  • 1
    You said you've tried several ways... what have you tried? Is the problem the time component of the `SignDate`? If so then `cast(SignDate as date)` – allmhuran Aug 31 '21 at 20:05
  • 1
    What happens if two rows have the same `SignDate` and `BranchId` values but different `EmployeeId` values? – Dai Aug 31 '21 at 20:08

1 Answers1

3
;WITH src AS 
(
  SELECT BranchID, EmployeeID, SignDate,
    rn = ROW_NUMBER() OVER (
      PARTITION BY BranchID, CONVERT(date, SignDate) 
      ORDER BY SignDate, EmployeeID -- break ties
    )
  FROM dbo.Attendance
  -- some kind of WHERE maybe
)
SELECT BranchID, EmployeeID, SignDate
  FROM src
  WHERE rn = 1
  ORDER BY BranchID, SignDate;

See also Retrieving n rows per group.

Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
  • 2
    Oh dang, I forgot about using `ROW_NUMBER` - I was mentally stuck in MS Access-mode for some reason. Upvoted! – Dai Aug 31 '21 at 20:09