![](/img/trans.png)
[英]Got orders and order_products tables.Should total price of order be stored in the orders table, or calculated based on the products quantity and price
[英]SQL that returns the total products quantity for orders with a status of delivered (different two tables)
我想獲取狀態為已交付的訂單的總產品數量。 我怎樣才能把它寫成一個單一的 sql 查詢?
表格1:
ID | order_id | 產品編號 | 數量 |
---|---|---|---|
1個 | 100001 | 123456780 | 3個 |
2個 | 100002 | 123456781 | 1個 |
3個 | 100002 | 123456782 | 5個 |
4個 | 100003 | 123456783 | 2個 |
表_2:
ID | order_id | 訂單狀態 | 訂購日期 |
---|---|---|---|
1個 | 100001 | 准備 | 2023-01-26 |
2個 | 100001 | 准備好的 | 2023-01-26 |
3個 | 100001 | 發表 | 2023-01-26 |
4個 | 100002 | 准備 | 2023-01-26 |
5個 | 100002 | 准備好的 | 2023-01-26 |
6個 | 100002 | 發表 | 2023-01-26 |
7 | 100003 | 准備 | 2023-01-26 |
8個 | 100004 | 准備 | 2023-01-26 |
9 | 100001 | 回來 | 2023-01-27 |
下面的 sql 查詢沒有按預期工作。 因為它不查看訂單的最新狀態:
SELECT SUM(t1.quantity) AS total
FROM table_1 t1
LEFT JOIN table_2 t2
ON t1.order_id = t2.order_id
WHERE t2.order_status = 'delivered'
結果:9 (3+1+5) 這個結果不正確。 因為訂單號 100001 的最后狀態是 Returned,所以它不應該將數字 3 添加到總數中。 正確的結果應該是 6 (1+5)。
您的查詢中有兩個問題:
ROW_NUMBER
window function 來做這樣的事情,它為按 order_date 順序排列的 order_id 的每個記錄分配一個排名(每個 order_id 的最后一個 order_date 的 rownum = 1)。 然后你可以過濾 rownum = 1。LEFT JOIN
,但您只需要可以在“ table_2 ”中找到並且嚴格滿足條件的行。 您應該使用INNER JOIN
。WITH cte AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY order_id
ORDER BY order_date DESC, id DESC) AS rn
FROM table_2
)
SELECT SUM(quantity)
FROM table_1 t1
INNER JOIN cte t2
ON t1.order_id = t2.order_id
AND t2.order_status = 'delivered'
AND t2.rn = 1
如果由於某種原因不能使用公用表表達式,處理它的等效方法是將 cte 轉換為子查詢:
SELECT SUM(quantity)
FROM table_1 t1
INNER JOIN (SELECT *, ROW_NUMBER() OVER(PARTITION BY order_id
ORDER BY date DESC, id DESC) AS rn
FROM table_2) t2
ON t1.order_id = t2.order_id
AND t2.order_status = 'delivered'
AND t2.rn = 1
Output:
SUM(數量) |
---|
6個 |
在此處查看演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.