2016-11-03 4 views
2

"in"연산자와 함께 "첫 번째 행 만 가져 오기"를 사용하려면 어떻게해야합니까?DB2에서 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  | 
------------------------- 

감사를 반환해야합니다!

+0

classic [태그 : 그룹당 최대 그룹 수] 문제 (그룹은 사람 별, "가장 큰"은 최근 날짜 임). –

답변

1

최신 사용자를 원하십니까? ROW_NUMBER() 사용

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 
+0

감사! 그것은 일했다! –

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 
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 
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 
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