日期:2014-05-18  浏览次数:20451 次

请教一SQL语句,做统计用
现有表
车牌号 范围 里程
津GB195警 市内 20
津GB190警 市内 0 
津GU0863 市内 20
津GU0863 市内 20
津GU0863 市外 20
津GB190警 市外 0
津GB190警 市外 0
津GB195警 市内 20
津GB195警 市内 20
津GB195警 市外 20
津GB195警 市内 20

想统计 每辆车的 出车次数、市内次数、市外次数、总里程

车牌号 市内 市外 里程
津GB195警 1 4 40
津GU0863 4 3 80

自己乱写了个select CarNum,count(CarNum) as cishu,sum(Convert(int,Miles)) as Miles,count(shiNW) as shiNW from qp_CarApply where shiNW='市内' group by CarNum

结果
车牌号 里程 市内  
鲁GB190警 1 0 1
鲁GB195警 4 80 4

不知道怎么把市外也显示出来 

请教高人
鲁GU0863 2 40 2

------解决方案--------------------
SQL code
select CarNum,
    count(CarNum) as [出车次数],
    count(case shiNW when '市内' then shiNW end) as [市内次数] ,
    count(case shiNW when '市外' then shiNW end) as [市外次数] ,
    sum(Convert(int,Miles)) as [总里程]
from qp_CarApply
group by CarNum

------解决方案--------------------
SQL code
select
 CarNum,
 count(CarNum) as [出车次数],
 sum(case shiNW when '市内' then 1 else 0 end) as [市内次数] ,
 sum(case shiNW when '市外' then 1 else 0 end) as [市外次数] ,
 sum(Convert(int,Miles)) as [总里程]
from
 qp_CarApply
group by
 CarNum