简体   繁体   中英

SQL - DB2 - Top multiple for each group

I need to create a query in DB2 that retrieves the highest X rows for each category or group.

Specifically, I have a set of employees and for each employee a set of values as such:

EMPLOYEE    DATE NUM     VAL
  001         ...         ..
  001         26          0
  001         27         15
  001         28          0
  003         01         44
  003         ...         ..
  003         07          0

Each employee will have several rows (multiples of 7 - they are days) and a value.

What I want to do is fetch the values for the LAST (highest) multiple of 7 (in employee #1 this would be 22-28, for employee #2 it would be 1-7).

My query is to check for all of the values on the last week for a employee to be = 0.

I'm writing this in DB2 and no query I have found out there is helping me with this.

Any ideas? (I am hoping this can be done with a simple query and not using a stored procedure)

Try this out:

WITH tbl AS (
SELECT employee, date_num, val,
  row_number() over(PARTITION BY employee ORDER BY date_num DESC) idx
FROM t
)
SELECT employee, date_num, val FROM tbl
WHERE idx = 1

A non-CTE and non-windowed function approach would be:

SELECT t1.* FROM t t1
JOIN (
  SELECT employee, max(date_num) date_num FROM t
  GROUP BY employee
) t2
ON t1.employee = t2.employee AND t1.date_num = t2.date_num

You can do this with window functions. It is a bit tricky to get the last seven days. Here is a method:

select e.*
from (select e.*,
             dense_rank() over (partition by employee order by floor((datenum - 1)/7) desc) as seqnum
      from employee e
     ) e
where seqnum = 1;

The expression floor((datenum - 1)/7) divides the rows into groups of seven, with the largest 7 values having a value of 1.

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