如何使用分组方式固定计数

时间:2019-06-19 09:23:10

标签: sql

我有这样的sql查询,

SELECT CAST(SUM(`op_total`) AS int) as total
FROM `dashboard_sales`
WHERE `op_status` IN ('settlement', 'capture') AND
      `order_date` between '2018-01-01' and '2019-06-30' AND
      `order_status` IN ('Ordered', 'Validated','Awaiting Packing','Packing Process','Ready to Ship','Shipped','Completed')

这就是结果

第一张图片:

enter image description here

但是因为某些order_id中存在重复数据,所以结果要比原始数据大

我已经使用group by进行了另一个查询,

SELECT CAST(SUM(`op_total`) AS int) as total 
FROM `dashboard_sales` 
WHERE 
`op_status` IN ('settlement', 'capture')  
AND `order_date` between '2018-01-01' and '2019-06-30'
AND `order_status` IN ('Ordered', 'Validated','Awaiting Packing','Packing Process','Ready to Ship','Shipped','Completed')
GROUP BY  `order_id`

但是结果是这样的

第二张图片:

enter image description here

使用分组方式时如何制作第一张图片?

1 个答案:

答案 0 :(得分:1)

在查询顶部使用子查询

select sum(total) as total
from
(
SELECT CAST(SUM(op_total) AS int) as total 
FROM dashboard_sales
WHERE op_status IN ('settlement', 'capture')  
AND order_date between '2018-01-01' and '2019-06-30'
AND order_status IN ('Ordered', 'Validated','Awaiting Packing','Packing Process','Ready to Ship','Shipped','Completed')
GROUP BY  order_id
)A