我有两个表,"[{'one': 'hi'}, {'one': 'hello'}]"
和orders
。
order_item
表:
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
由于每个订单可以包含多个产品,因此Id OrderTotal Quantity
12001 2001 2
12002 2001 1
12003 2002 1
12004 2003 1
12005 2003 1
表可以为单个订单创建多个记录。
我想通过查询获得结果
order_item
我写了一个查询
OrderCount Quantity OrderTotal DeliveryCharge
3 6 3300 370
有结果
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'
但是现在我想要OrderCount Quantity OrderTotal
3 6 3300
DeliveryCharge
表的总和,所以我必须像我为orders
写的那样写选择子查询。
有没有一种很好的方法可以在不使用多个子查询的情况下使用单个查询找到它?
答案 0 :(得分:0)
将子查询放在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;
答案 1 :(得分:0)
使用此
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