日期:2014-05-17  浏览次数:20610 次

新人请教,请问这个SQL语句应该怎么写?
公司名 company_name;
客户类型 type; 1-至尊VIP 2-普通VIP 3-会员 4-游客;
加入时间 inserttime;

现在我想知道每间公司在某一时间段(例如2013-1-1至2013-2-1)内每种类型新加入客户的总数;
最终实现的效果如下:
公司名   客户类型1   客户类型2   客户类型3   客户类型4

请问语句怎么写?谢谢大家了

------解决方案--------------------
select company_name,case when 客户类型=1 then 1 else 0 end as 客户类型1,
case when 客户类型=2 then 1 else 0 end as 客户类型2,
case when 客户类型=3 then 1 else 0 end as 客户类型3,
case when 客户类型=4 then 1 else 0 end as 客户类型4,
COUNT(*) as 总数
from tb
where inserttime between StartTime and EndTime
group by company_name

------解决方案--------------------
漏写了函数,补:
select company_name,sum(case when 客户类型=1 then 1 else 0 end) as 客户类型1,
sum(case when 客户类型=2 then 1 else 0 end) as 客户类型2,
sum(case when 客户类型=3 then 1 else 0 end) as 客户类型3,
sum(case when 客户类型=4 then 1 else 0 end) as 客户类型4,
COUNT(*) as 总数
from tb
where inserttime between StartTime and EndTime
group by company_name