[英]Subtracting rows based on condition
假設我有一個如下所示的表:
OrderNumber OrderType
1 D
1 D
1 R
2 D
2 R
3 D
3 D
3 D
3 R
3 R
結果應該是:
OrderNumber OrderType
1 D
3 D
在這里,R 表示從訂單中刪除一行。 我們在第一個示例中看到我們有 2 個 D 和 1 個 R,因此我們刪除了一個 D 替換為 1 個 D。在 SQL 中有沒有辦法做到這一點?
如果你的 mysql 版本支持 cte 和窗口函數,我們可以嘗試使用ROW_NUMBER
窗口函數為每個OrderNumber
OrderType
制作行號
然后使用EXISTS
子查詢判斷OrderType = D
行數需要大於R
的最大行數。
with cte as (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY OrderNumber,OrderType) rn,
COUNT(*) OVER(PARTITION BY OrderNumber,OrderType) cnt
FROM T
)
SELECT c1.OrderNumber,
c1.OrderType
FROM cte c1
WHERE EXISTS (
SELECT 1
FROM cte c2
WHERE c1.OrderNumber = c2.OrderNumber
AND c2.OrderType = 'R'
AND c1.rn > c2.cnt
)
AND c1.OrderType = 'D'
您可以使用窗口功能。 這是 sqlite 語法,但 mysql 應該相當接近。
select A.OrderNumber,A.OrderType
from (select OrderNumber,OrderType,row_number() over(partition by OrderNumber) as RN
from b where OrderType='D') A
left join
(select sum(case when OrderType='R' then 1 else 0 end) as cnt,OrderNumber
from b group by OrderNumber) B
on A.OrderNumber=B.OrderNumber
where A.rn>B.cnt;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.