计算一个范围内发生的采购订单的数量

Count the number of Purchase Orders that occur within a Range

我有一个 table (order_lines),其中包含 (order_lines_order_header_id) 这是 PO 编号,我有 (order_lines.accounting_total) 这是值具体采购订单行。

我需要将每个 'order_header_id' 的总和分为四个范围。第一个范围是 500 美元以下的采购订单。第二个是 501 美元到 1000 美元之间的采购订单。第三个区间在 1001 美元到 10,000 美元之间。第四是所有超过$10,000的采购订单。

我需要这样的结果:

Count of POs under 0 -- ####
Count of POs over 1 Under 00-- ####
Count of POs over ,001 Under ,000 --####
Count of POs over ,000-- ####

这是我目前拥有的,但没有用:

SELECT COUNT(order_lines.order_header_id) where SUM(order_lines.accounting_total) <= 500 as Orders_Under_500
From order_lines

有什么想法吗?

首先,您需要一个子查询来计算每个订单的总金额。然后您需要另一个查询来获取您要查找的计数:

select (case when total < 500 then 'Less than 0'
             when total < 1000 then 'Between 0 and ,000'
             when total < 10000 then 'Between ,000 and ,000'
             else 'Over ,000'
        end) as grp,
       count(*) as Numorders
from (select ol.order_header_id, sum(accounting_total) as total
      from order_lines ol
      group by ol.order_header_id
     ) ol
group by (case when total < 500 then 'Less than 0'
               when total < 1000 then 'Between 0 and ,000'
               when total < 10000 then 'Between ,000 and ,000'
               else 'Over ,000'
          end);

您的查询顺序不对,正确的格式是:

SELECT COUNT(order_header_id) 
FROM order_lines 
WHERE SUM(accounting_total) <= 500 

但是,需要一个不同的查询来select您在一个查询中需要的所有内容:

SELECT
SUM(CASE WHEN accounting_total <500 THEN 1 ELSE 0 END) AS `500`,
SUM(CASE WHEN accounting_total BETWEEN 500 AND 1000 THEN 1 ELSE 0 END) AS `500-1000`
SUM(CASE WHEN accounting_total BETWEEN 1000 AND 10000 THEN 1 ELSE 0 END) AS `1000-10000`
SUM(CASE WHEN accounting_total >10000 THEN 1 ELSE 0 END) AS `10000`
FROM order_lines

或者(未测试):

SELECT COUNT(order_header_id) 
FROM order_lines 
WHERE SUM(accounting_total) <= 500 
OR (SUM(accounting_total) > 500 AND SUM(accounting_total) <= 1000 )
OR (SUM(accounting_total) > 1000 AND SUM(accounting_total) <= 10000 )
OR SUM(accounting_total) > 10000
GROUP BY  COUNT(order_header_id)

希望对您有所帮助。