原始数据
+---------+--------+------------+
| ID | STATUS | DATE |
+---------+--------+------------+
| ABC1234 | P | 2020-01-01 |
| ABC1234 | P | 2020-01-02 |
| ABC1234 | B | 2020-01-03 |
| ABC1234 | A | 2020-01-04 |
| ABC1234 | A | 2020-01-05 |
| BCD | P | 2020-01-01 |
| BCD | P | 2020-01-02 |
| BCD | P | 2020-01-03 |
| BCD | B | 2020-01-04 |
| BCD | A | 2020-01-05 |
| 12XY | P | 2020-01-01 |
| 12XY | P | 2020-01-02 |
| 12XY | P | 2020-01-03 |
| 12XY | B | 2020-01-04 |
| 12XY | B | 2020-01-05 |
+---------+--------+------------+
我想要的结果
+-----+--------+------------+
| ID | STATUS | DATE |
+-----+--------+------------+
| BCD | B | 2020-01-04 |
| BCD | A | 2020-01-05 |
+-----+--------+------------+
如何找到最新记录状态为a,第二个最新记录状态为b的结果?
在下面试用过,但仍然不知道如何获取id=bcd
select ROW_NUMBER()
OVER (PARTITION BY ID ORDER BY date2 DESC) AS rownum
,*
into testingtable
from mytable
WHERE status in ('b', 'a')
2条答案
按热度按时间csbfibhn1#
如何查找最新记录
Status=A
,和第二个最新记录Status=B
?您可以使用窗口函数和一些布尔逻辑:
tvmytwxo2#
从子查询中删除where子句并使用布尔逻辑: