简体   繁体   中英

Finding first occurence of multiples value in every group sort by date in SQL

I have a table with every operations that appends before an event group by another value.

There is only 3 operations: R, E, P

+ ----------+----------+-----------+------------------------+
| Rollcycle | Blocking | Operation | Order                  |
+ ----------+----------+-----------+------------------------+
| 1         | 3        | R         | 4                      |
| 1         | 3        | P         | 3                      |
| 1         | 3        | E         | 2                      |
| 1         | 3        | R         | 1                      |
| 1         | 2        | P         | 3                      |
| 1         | 2        | E         | 2                      |
| 1         | 2        | R         | 1                      |
| 1         | 1        | R         | 1                      |
| 2         | 1        | E         | 2                      |
| 2         | 1        | R         | 1                      |
+ ----------+----------+-----------+------------------------+

I want to know which operations occurs before every blocking group by Rollcycle. I need to do this in access SQL.

Output

+ ----------+----------+---+---+---+
| Rollcycle | Blocking | R | E | P |
+ ----------+----------+---+---+---+
| 1         | 1        | 1 | 0 | 0 |
| 1         | 2        | 0 | 1 | 1 |
| 1         | 3        | 1 | 0 | 0 |
| 2         | 1        | 1 | 1 | 0 |
+ ----------+----------+---+---+---+

I could not find anything similar. It's maybe too specific.

Please help :)

EDIT: back to original table

If I followed you correctly, you can filter on records where order is greater or equal than blocking , and then do conditional aggregation:

select
    rollcycle,
    blocking,
    max(iif(operation = 'R', 1, 0)) R,
    max(iif(operation = 'E', 1, 0)) E,
    max(iif(operation = 'P', 1, 0)) P
from mytable 
where order >= blocking
group by rollcycle, blocking

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