我有两个表,一个是订单,第二个是order_product,其中我必须找到订单数量,产品数量,totalamount对应商店使用商店ID我已经成功找到订单数量和产品数量但是我的totalamount不正确。
订单:
...........................
order_id or_total_amt
...........................
1 10
2 10
3 10
order_product
.................................
op_id op_order_id st_id
.................................
1 1 1
2 2 2
3 3 1
4 3 1
我想要低于输出但是我的totalamount值出错了它将会出现30,但是正确的值是20,我在右下方输出中提到过。
我想要的输出:
.........................................
st_id orders product totalmount
.........................................
1 2 3 20
2 1 1 10
我已经尝试过以下查询,它给出了30个值为totalamount的错误。
SELECT `op_st_id`,count(distinct orders.`order_id`)as orders,count(order_product.op_pr_id) as product
,sum(orders.or_total_amt) as totalamount from orders
inner JOIN order_product on orders.order_id=order_product.op_order_id
group by `op_st_id`
答案 0 :(得分:2)
SELECT
`st_id`,
count(DISTINCT orders.`order_id`) AS orders,
count(order_product.op_id) AS product,
count(DISTINCT orders.`order_id`)*(sum(orders.or_total_amt)/count(order_product.op_id)) AS totalamount
FROM
orders
INNER JOIN order_product ON orders.order_id = order_product.op_order_id
GROUP BY
`st_id`