[英]How to apply aggregate function only on distinct records
I have two tables, orders
and order_item
. 我有两个表,
orders
和order_item
。
orders
table: orders
表:
Id Total DeliveryCharge Status DeliveryDate
2001 600 120 30 2015-09-01 11:56:32
2002 1500 150 30 2015-09-09 09:56:32
2003 1200 100 30 2015-09-30 08:05:32
order_item
table: order_item
表:
Id OrderTotal Quantity
12001 2001 2
12002 2001 1
12003 2002 1
12004 2003 1
12005 2003 1
As each order can contain multiple products, that way order_item
table could multiple records for a single order. 由于每个订单可以包含多个产品,因此
order_item
表可以为单个订单提供多个记录。
I want to get result by the query is 我想通过查询获取结果是
OrderCount Quantity OrderTotal DeliveryCharge
3 6 3300 370
I wrote a query 我写了一个查询
select count(distinct od.Id) as OrderCount,
sum(oi.Quantity) as Quantity,
(select sum(ord.OrderTotal) from orders ord
where ord.DeliveryDate between '2015-09-01' and '2015-10-01' and ord.Status=30 ) as OrderTotal
from orders od
join Order_items oi on od.Id=oi.orderId
where od.Status=30
and od.DeliveryDate between '2015-09-01' and '2015-10-01'
which has the result 结果
OrderCount Quantity OrderTotal
3 6 3300
But now I want the sum of DeliveryCharge
of orders
table, so again I have to write select sub-query as I wrote for OrderTotal
. 但是现在我想要
orders
表的DeliveryCharge
的总和,因此我再次必须为OrderTotal
编写select子查询 。
Is there a good way to find it with single query without using multiple sub-queries? 有没有一种好的方法可以通过单个查询而不使用多个子查询来找到它?
Put subqueries in the from
clause: 将子查询放在
from
子句中:
select o.OrderCount, o.OrderTotal, o.OrderDeliveryCharge, oi.quantity
from (select count(*) as OrderCount, sum(Total) as OrderTotal,
sum(DeliveryCharge) as OrderDeliveryCharge
from orders
) o cross join
(select sum(quantity) as quantity
from order_item
) oi;
Use this 用这个
SELECT SUM(oi.oc) AS 'OrderCount', SUM(oi.q) AS 'Quantity', SUM(o.total) AS 'OrderTotal', SUM(o.deliverycharge) AS 'DeliveryCharge'
FROM
orders o INNER JOIN
(SELECT ordertotal, COUNT(DISTINCT(ordertotal)) AS oc, SUM(quantity) AS q FROM order_item GROUP BY 1) oi ON o.id=oi.ordertotal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.