我有下表。我希望每章一个值。 (我有带case表达式的SQL,但返回错误,所以我不会显示以避免混淆。)
条件PER章节:
A-END_DT不为空,并且ROLE =红色且USERID不为空,然后USERID的最后一行值
B-END_DT为NULL,并且角色=红色,然后是用户ID的最后一行值
TableP
END_DT ROLE PK USERID CHAPTER
01/10/19 RED 101 5 1
01/10/19 BLUE 102 5 1
01/10/19 RED 103 7 1
01/10/19 RED 104 1
RED 105 8 2
BLUE 106 9 2
BLUE 107 5 3
预期结果:
CHAPTER USERID
1 7
2 8
答案 0 :(得分:0)
尝试一下:
select chapter, userID
from
(
select top 1 chapter, last_value(userID) over(order by userID desc)as rw, userID
from sample
where END_DT is NOT NULL AND ROLE = 'RED'
union
select top 1 chapter, last_value(userID) over(order by userID desc)as rw, userID
from sample
where END_DT is NULL AND ROLE = 'RED'
) w
答案 1 :(得分:0)
canvas.delete("all")
的行。使用Oracle的PK
进行排名:
KEEP LAST
或者,如果需要标准的SQL查询,请使用select
chapter,
max(userid) keep (dense_rank last order by case when end_dt is null then 1 else 2 end, id)
from mytable
where role = 'RED' and userid is not null
group by chapter
order by chapter;
:
ROW_NUMBER