[英]How to get total sum from one table with inner join in mysql
我有兩個表,一個是訂單,第二個是 order_product,我必須在其中使用買家 ID 找出與客戶對應的訂單數、產品數、總金額,我已成功從中找出訂單數和產品數,但我的總金額不是來對了。
訂單:
.......................................
order_id or_buyer_id or_total_amt
.......................................
1 21 10
2 22 10
3 21 10
訂單_產品
.................................
op_id op_order_id op_buyer_id
.................................
1 1 21
2 1 21
3 2 22
4 3 21
我想要低於輸出,但我的 totalamount 值出錯了,它是 30,但正確的值是 20,我在下面的正確輸出中提到過。
我想要的輸出:
............................................
or_buyer_id orders product totalmount
...........................................
21 2 3 20
22 1 1 10
我已經嘗試了下面的查詢,它給出了 30 的 totalamount 值,這是錯誤的。
SELECT o.or_buyer_id
, count(DISTINCT o.order_id) as orders
, count(op.op_id) as product
, SUM(o.or_total_amt) as totalamount
FROM orders as o
JOIN order_product as op
on op.op_order_id = o.order_id
and o.or_buyer_id = op.op_buyer_id
group
by o.or_buyer_id
一種方法是從子查詢中的order_product
表中刪除重復的行。 然后,像您已經在做的那樣將其加入orders
。 這里的一個小技巧是,在刪除子查詢中的重復項時,我們保持order_product
表中原始記錄的數量。 這是因為product
列反映了真實的原始記錄數。 但是totalamount
不反映重復項,因此我們將該數量與刪除重復項相加。
SELECT
t1.op_buyer_id,
COUNT(DISTINCT t1.op_order_id) AS orders,
SUM(t1.cnt) AS product,
SUM(t2.or_total_amt) AS totalamount
FROM
(
SELECT op_order_id, op_buyer_id, COUNT(*) AS cnt
FROM order_product
GROUP BY op_order_id, op_buyer_id
) t1
INNER JOIN orders t2
ON t1.op_order_id = t2.order_id AND
t1.op_buyer_id = t2.or_buyer_id
GROUP BY
t1.op_buyer_id
ORDER BY
t1.op_buyer_id;
您應該在內連接中使用子查詢,而不是直接引用 order_product 表:
嘗試用 order_product 替換
(SELECT DISTINCT op_order_id, op_buyer_id
FROM order_product) AS op
這將刪除給您錯誤總和的重復項。
我還引入了一個子查詢來獲取正確的產品值:
SELECT count(op_order_id) FROM order_product WHERE order_id = o.order_id AND op_buyer_id = o.or_buyer_id) as product
最終的 SQL 是:
SELECT o.`or_buyer_id`,
count(DISTINCT o.`order_id`) as orders,
(SELECT count(op_order_id) FROM order_product WHERE order_id = o.order_id AND op_buyer_id = o.or_buyer_id) as product,
SUM(o.`or_total_amt`) as totalamount
FROM `orders` as o
INNER JOIN (SELECT DISTINCT op_order_id,
op_buyer_id
FROM order_product) AS op
ON op.op_order_id=o.order_id AND o.or_buyer_id = op.op_buyer_id
GROUP BY o.`or_buyer_id`
你應該使用這個子查詢
SELECT tbl.op_buyer_id, COUNT(DISTINCT tbl.op_order_id) AS orders, SUM(tbl.cont) AS product, SUM(tbl2.or_total_amt) AS totalamount FROM ( SELECT op_order_id, op_buyer_id, COUNT(*) AS cont FROM order_product GROUP BY op_order_id, op_buyer_id ) tbl INNER JOIN orders tbl2 ON tbl.op_order_id = tbl2.order_id AND tbl.op_buyer_id = tbl2.or_buyer_id GROUP BY tbl.op_buyer_id ORDER BY tbl.op_buyer_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.