SQL选择大小写和?

SQL选择大小写和?,sql,sql-server,Sql,Sql Server,这可能是一个非常基本的问题,但我正在尝试生成给定月份的订单总值(不包括运费和税费)的柱状图 不幸的是,表中没有总计的列,因此需要从小计减去任何折扣或应用的积分来计算 我认为这样可能会起作用,但我认为在case语句中对SUM表达式的计算不正确,因为它只返回“else”条件 select t.range as [price range], COUNT(*) as [orders] from ( select case when SUM(o.subtotal - o.disco

这可能是一个非常基本的问题,但我正在尝试生成给定月份的订单总值(不包括运费和税费)的柱状图

不幸的是,表中没有总计的列,因此需要从小计减去任何折扣或应用的积分来计算

我认为这样可能会起作用,但我认为在case语句中对SUM表达式的计算不正确,因为它只返回“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中,顺便说一句。

请为您的案例statmenets尝试此格式

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

您也可以在一个查询中完成这一切。实际上不需要子查询来完成这项工作

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 
这应该起作用:

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

谢谢-我没有意识到这只是一个简单的语法错误。这对我有用。