|
buy_user_id |
sell_user_id |
|
1 |
10 |
|
2 |
11 |
|
3 |
12 |
|
10 |
4 |
|
11 |
5 |
|
12 |
6 |
|
10 |
10 |
buy와 sell을 모두한 유저의 수를 구하고싶은데 어떻게 해야할지 도무지 감이 안옵니다 ㅠ
위 경우 총 3명이라고 구하고 싶습니다.
buy_user_id = sell_user_id 로 조건을 걸자니, 자기자신에게 팔고 산 것이라 그 케이스는 제외하고싶어서요.
초보에게 도움 부탁드립니다 ㅠㅠ
효율적인 쿼리는 다른분들이 알려주실거라 믿고
제가 생각해본 내용 공유드려요
with tmp_a as (
select 1 as buyid, 10 as sellid union all
select 2 , 11 union all
select 3 , 12 union all
select 10, 4 union all
select 11, 5 union all
select 12, 6 union all
select 10, 10
)
select sellid /* 판매/구매 모두 한 id */
from (
select sellid
from tmp_a
where buyid != sellid
group by sellid
) selllist /* 판매자 id list */
inner join (
select buyid
from tmp_a
where buyid != sellid
group by buyid
) buylist /* 구매자 id list */
on selllist.sellid = buylist.buyid /* 판매/구매 모두 한 list */
다른형태로 작성한것도 공유드려요
with tmp_a as (
select 1 as buyid, 10 as sellid union all
select 2 , 11 union all
select 3 , 12 union all
select 10, 4 union all
select 11, 5 union all
select 12, 6 union all
select 10, 10 union all
select 4 , 4 union all
select 3 , 3
)
select buyid from tmp_a aa
where aa.buyid != aa.sellid
and exists (select 1 from tmp_a bb
where aa.buyid = bb.sellid
and bb.buyid != bb.sellid)
group by buyid
감사합니다! 위에 써주신거대로 실제 데이터에 넣어가지고 건수 뽑는거 성공했는데 아래 작성해주신 짧은 쿼리로도 이해해보고 실행시켜보겠습니다. 너무 감사합니다 (_ _)!!
WITH t AS
(
SELECT 1 buy_user_id, 10 sell_user_id FROM dual
UNION ALL SELECT 2, 11 FROM dual
UNION ALL SELECT 3, 12 FROM dual
UNION ALL SELECT 10, 4 FROM dual
UNION ALL SELECT 11, 5 FROM dual
UNION ALL SELECT 12, 6 FROM dual
UNION ALL SELECT 10, 10 FROM dual
)
SELECT COUNT(DISTINCT a.buy_user_id) cnt
FROM t a
, t b
WHERE a.buy_user_id = b.sell_user_id
AND b.buy_user_id != b.sell_user_id
;