MS SQL案例内部计数

时间:2017-09-19 15:43:44

标签: mysql sql-server

我没有使用MS SQL的经验,而且我试图转换我的MySQL查询,我正在试图解决问题:

select 
    m.Customer,
    count(if(c.AtFault="Me",1,null)) 'MeLate',
    count(if(c.AtFault="You",1,null)) 'YouLate',
    count(*) 'Total'
from m
left join r on m.OrderNumber = r.OrderNumber
left join c on r.ReasonCodeID = c.ID
group by m.Customer

这就是我想在MS SQL上运行的东西:

select 
    m.Customer
    count(CASE WHEN c.AtFault="Me" THEN 1 ELSE null) 'MeLate',
    count(CASE WHEN c.AtFault="You" THEN 1 ELSE null) 'YouLate',
    count(*) 'Total'
from m
left join r on m.OrderNumber = r.OrderNumber
left join c on r.ReasonCodeID = c.ID
group by m.Customer

但这会引发无意义的错误:

  

SQL错误(102):')'附近的语法不正确。

2 个答案:

答案 0 :(得分:2)

三个错误:

END结束时您遗漏了CASE WHEN

您必须使用单引号代替双倍。

m.Customer

之后忘记逗号

试试这个:

    select 
        m.Customer,
        count(CASE WHEN c.AtFault='Me' THEN 1 ELSE null END) MeLate,
        count(CASE WHEN c.AtFault='You' THEN 1 ELSE null END) YouLate,
        count(*) Total
    from m
    left join r on m.OrderNumber = r.OrderNumber
    left join c on r.ReasonCodeID = c.ID
    group by m.Customer

答案 1 :(得分:1)

在那里缺少你可以尝试总和而不是计数

select 
    m.Customer,
    sum(CASE WHEN c.AtFault='Me' THEN 1 ELSE 0 end) MeLate,
    sum(CASE WHEN c.AtFault='You' THEN 1 ELSE 0 end) YouLate,
    count(*) Total
from m
left join r on m.OrderNumber = r.OrderNumber
left join c on r.ReasonCodeID = c.ID
group by m.Customer