简体   繁体   中英

Sql Query - Generating "lot" numbers on a list for each group of N items with the same ID

I've come across a situation where I need to write a query, and I have no clue what the best route is.

So assume I've got data like this:

+------------+-------------------+
| EmployeeID |  ProjectStartDate |
+------------+-------------------+
| 1          |  01/01/2017       |
| 1          |  02/02/2017       |
| 1          |  03/03/2017       |
| 1          |  04/04/2017       |
| 1          |  05/05/2017       |
| 1          |  06/06/2017       |
| 1          |  07/07/2017       |
| 2          |  01/01/2017       |
| 2          |  02/02/2017       |
| 2          |  03/03/2017       |
| 2          |  04/04/2017       |
+------------+-------------------+

I need to generate project "lots" for each employee, but the lots have a lot number associated with each group of N (let's say 5 here) items. So I need a query that can group by EmployeeID, sort by ProjectStartDate, and then dynamically group each employee's results into groups of 5, assigning an incremental count to each group. So the end result would be like this:

+------------+-------------+------------------+
| LotNumber  | EmployeeId  | ProjectStartDate |
+------------+-------------+------------------+
| 1          | 1           | 01/01/2017       |
| 1          | 1           | 02/02/2017       |
| 1          | 1           | 03/03/2017       |
| 1          | 1           | 04/04/2017       |
| 1          | 1           | 05/05/2017       |
+------------+-------------+------------------+
| 2          | 1           | 06/06/2017       |
| 2          | 1           | 07/07/2017       |
+------------+-------------+------------------+
| 1          | 2           | 01/01/2017       |
| 1          | 2           | 02/02/2017       |
| 1          | 2           | 03/03/2017       |
| 1          | 2           | 04/04/2017       |
+------------+-------------+------------------+

Normally, I'd just create a table for lots, but the lot numbers can change dynamically since they go off of the Date with the first lots generated from the oldest dates. So adding or deleting projects will change every lot number after it.

Does anyone have any thoughts on an efficient way to do this?

A combination of ROW_NUMBER and integer division should work:

WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY EmployeeID ORDER BT ProjectStartDate)
    FROM dbo.YourTable
)
SELECT  (RN -1 )/5 + 1 LotNumber,
        EmployeeID,
        ProjectStartDate
FROM CTE
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM