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

我们两清 提交于 2020-01-11 13:05:50

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/59196643/finding-first-occurence-of-multiples-value-in-every-group-sort-by-date-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!