抱歉,這是我的第一篇文章-如果有什么不合理的地方,請告訴我!
我正在嘗試使用特定代碼 XXX 計算訂單數量
假設表 A 看起來像這樣
|ORDER ID | ITEM CODE |
123 XXX
123 YYY
123 YYY
456 XXX
456 XXX
456 XXX
789 XXX
000 YYY
我想要的輸出是:
- 命令 123 和 000 不計算在內
- 并命令 456 和 789 各計為 1
我只想要專案代碼為 XXX 的唯一訂單的數量
所以最終查詢的計數/輸出應該是 2
目前我所擁有的是
select order_id, item code, count(order_id) from table a
where item code = 'XXX'
group by order_id, item code
order by count(order_id)
輸出我以下內容
ORDER_ID | ITEM CODE | COUNT(ORDER_ID)
123 XXX 1
345 XXX 3
789 XXX 1
這是錯誤的,因為我想要如上所述的輸出
提前致謝!
uj5u.com熱心網友回復:
select order_id
from table_a
group by order_id
having min(item_code) = 'XXX'
and max(item_code) = 'XXX'
uj5u.com熱心網友回復:
好像你想要這個:
select distinct order_id , item_code , 1 as count
from table t1
where not exists (
select 1 from table t2
where t1.order_id = t2.order_id
and t2.item_code <> 'XXX'
)
每個問題的計數始終為 1
uj5u.com熱心網友回復:
一種選擇是使用反連接。例如:
select distinct t.order_id, 1 as cnt
from table_a t
left join table_a u on u.order_id = t.order_id and u.item_code <> 'XXX'
where t.item_code = 'XXX' and u.order_id is null
結果:
ORDER_ID CNT
--------- ---
789 1
456 1
請參閱db<>fiddle 上的運行示例。
編輯
要僅獲取總計數,請按如下所示調整查詢:
select count(distinct t.order_id) as cnt
from table_a t
left join table_a u on u.order_id = t.order_id and u.item_code <> 'XXX'
where t.item_code = 'XXX' and u.order_id is null
結果:
CNT
---
2
請參閱db<>fiddle 上的運行示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/327530.html
