我有一个表 (order_lines),其中包含 (order_lines_order_header_id),即采购订单号,并且我有 (order_lines.accounting_total),它是特定采购订单行的值。
我需要将每个“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
有什么想法吗?
最佳答案
首先,您需要一个子查询来计算每个订单的总金额。然后您需要另一个查询来获取您要查找的计数:
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);
关于sql - 计算某个范围内发生的采购订单数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712086/