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

时间:2015-04-18 02:03:27

标签: sql count sum

我有一个表(order_lines)包含(order_lines_order_header_id),它是PO号,我有(order_lines.accounting_total),它是特定PO行的值。

我需要对每个' order_header_id'的总和进行分组。分为四个范围。第一个范围是低于500美元的采购订单。第二个是501美元到1000美元之间的采购订单。第三个范围在1001美元到10,000美元之间。第四个是超过10,000美元的PO。

我需要将结果看起来像这样:

Count of POs under $500 -- ####
Count of POs over $501 Under $1000-- ####
Count of POs over $1,001 Under $10,000 --####
Count of POs over $10,000-- ####

这是我到目前为止所做的,但它不起作用:

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

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

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

select (case when total < 500 then 'Less than $500'
             when total < 1000 then 'Between $500 and $1,000'
             when total < 10000 then 'Between $1,000 and $10,000'
             else 'Over $10,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 $500'
               when total < 1000 then 'Between $500 and $1,000'
               when total < 10000 then 'Between $1,000 and $10,000'
               else 'Over $10,000'
          end);

答案 1 :(得分:0)

您的查询不符合规定,正确的格式为:

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

但是,需要一个不同的查询来在一个查询中选择所需的全部内容:

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)

希望有所帮助。