简体   繁体   中英

How to apply aggregate function only on distinct records

I have two tables, orders and order_item .

orders table:

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:

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.

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 .

Is there a good way to find it with single query without using multiple sub-queries?

Put subqueries in the from clause:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM