这可能是一个非常基本的问题,但我试图在给定的月份内生成订单总值(不包括运费和税收)的直方图。
不幸的是,表格中没有列的总数,因此需要根据小计减去任何折扣或应用信用额来计算。
我认为这样的事情可能有用,但我不认为SUM表达式在case语句中正确评估,因为它只返回" else"条件。
select t.range as [price range], COUNT(*) as [orders]
from (
select case
when SUM(o.subtotal - o.discount - o.credit) between 0 and 49.99 then '0-49.99'
when SUM(o.subtotal - o.discount - o.credit) between 50 and 99.99 then '50-99.99'
when SUM(o.subtotal - o.discount - o.credit) between 100 and 149.99 then '100-149.99'
when SUM(o.subtotal - o.discount - o.credit) between 150 and 199.99 then '150-199.99'
else '200+' end as range
from dbo.[order] o
where o.date_placed BETWEEN '4/1/14' AND '4/30/14') t
group by t.range
我做错了什么?这是在MS SQL Server btw。
答案 0 :(得分:2)
为您的案例陈述试用此格式
select
sum(case when o.subtotal - o.discount - o.credit between 0 and 49.99 then 1 else 0 end) as bucket1,
sum(case when o.subtotal - o.discount - o.credit between 50 and 99.99 then 1 else 0 end) as bucket2,
sum(case when o.subtotal - o.discount - o.credit between 100 and 149.99 then then 1 else 0 end) as bucket3,
sum(case when o.subtotal - o.discount - o.credit between 150 and 199.99 then 1 else 0 end) as bucket4,
sum(case when o.subtotal - o.discount - o.credit >= 200 then 1 else 0 end) as bucket5
答案 1 :(得分:1)
这应该有效:
select t.range as [price range], COUNT(*) as [orders]
from (
select case
when (o.subtotal - o.discount - o.credit) between 0 and 49.99 then '0-49.99'
when (o.subtotal - o.discount - o.credit) between 50 and 99.99 then '50-99.99'
when (o.subtotal - o.discount - o.credit) between 100 and 149.99 then '100-149.99'
when (o.subtotal - o.discount - o.credit) between 150 and 199.99 then '150-199.99'
else '200+' end as range
from dbo.[order] o
where o.date_placed BETWEEN '4/1/14' AND '4/30/14') t
group by t.range
答案 2 :(得分:0)
您也可以在一个查询中完成所有工作。实际上不需要子查询来执行此操作。
select
case SUM(o.subtotal - o.discount - o.credit)
when between 0 and 49.99 then '0-49.99'
when between 50 and 99.99 then '50-99.99'
when between 100 and 149.99 then '100-149.99'
when between 150 and 199.99 then '150-199.99'
else '200+' end
as PriceRange
, COUNT(*) as [orders]
from dbo.[order] o
where o.date_placed BETWEEN '4/1/14' AND '4/30/14'
group by case SUM(o.subtotal - o.discount - o.credit)
when between 0 and 49.99 then '0-49.99'
when between 50 and 99.99 then '50-99.99'
when between 100 and 149.99 then '100-149.99'
when between 150 and 199.99 then '150-199.99'
else '200+' end