仅在DB2中使用IN操作获取第一行

时间:2016-11-03 08:52:23

标签: sql db2 greatest-n-per-group

如何与“in”运算符结合使用“仅获取第一行”?

之类的东西
select user_id, item_name as last_item_name 
from sale 
where user_id in (1,2) 
order by date desc 
fetch first row only

我想让它返回每个人购买的最后一项? 例如:在

上运行查询
--------------------------------
id | user_id | item_name| date |
1  | 1       | pen      | 01/01|
2  | 1       | book     | 02/01|
3  | 2       | book     | 01/01|
4  | 2       | computer | 02/01|
--------------------------------

应该返回

user_id | last_item_name|
1       | book          |
2       | computer      |
-------------------------

谢谢!

5 个答案:

答案 0 :(得分:1)

所以你想要每个用户最新?使用SELECT * FROM ( SELECT t.*, ROW_NUMBER() OVER(PARTITION BY t.user_id ORDER BY t.date DESC) as rnk FROM sale t WHERE t.user_id IN(1,2)) s WHERE s.rnk = 1

{{1}}

答案 1 :(得分:0)

解决方案1 ​​

with uniquserid as (
select distinct user_id from sale 
)
select f1.user_id , f3.item_name 
from uniquserid f1
inner join lateral 
(
select * from sale f2
where f1.user_id =f2.user_id 
ORDER BY f2.date DESC
fetch first rows only 
) f3 on 1=1

答案 2 :(得分:0)

解决方案2

select f1.user_id , f3.item_name 
from 
(select distinct user_id from sale) f1
inner join lateral 
(
select * from sale f2
where f1.user_id =f2.user_id
ORDER BY f2.date DESC
fetch first rows only 
) f3 on 1=1

答案 3 :(得分:0)

解决方案3

 with uniquserid as (
 select distinct user_id from sale 
 )
 select f1.user_id , (select f2.item_name from sale f2 where f1.user_id =f2.user_id ORDER BY f2.date DESC
 fetch first rows only) as item_name 
 from uniquserid f1

答案 4 :(得分:0)

解决方案4

select f1.user_id , (select f2.item_name from sale f2 where f1.user_id =f2.user_id ORDER BY f2.date DESC
fetch first rows only) as item_name 
from (select distinct user_id from sale) f1