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

汇总数据 急啊
表结构字段和数据如下:
CustomerName     ArriveTime     FactTime   --客户名称     应到达时间   实际到达时间  
  联想集团               08:00               08:15
  康佳                       09:00               09:30
  康佳                       09:00               09:00
  康佳                       09:00               09:20
  联想集团               08:00               08;00
  TCL                         08:30               09;00

如果   ArriveTime小于FactTime就代表迟到
要求汇总结果如下
客户名称   迟到次数   总次数
联想集团         1               2
康佳                 2               3
TCL                   1               1

------解决方案--------------------
create table test(CustomerName varchar(20),ArriveTime varchar(10),FactTime varchar(10))
insert test select '联想集团 ', '08:00 ', '08:15 '
union all select '康佳 ', '09:00 ', '09:30 '
union all select '康佳 ', '09:00 ', '09:00 '
union all select '康佳 ', '09:00 ', '09:20 '
union all select '联想集团 ', '08:00 ', '08:00 '
union all select 'TCL ', '08:30 ', '09:00 '

select 客户名称=CustomerName,
迟到次数=sum(case when CustomerName=a.CustomerName and ArriveTime <a.FactTime then 1 else 0 end),
总次数=count(*) from test a
group by CustomerName

客户名称 迟到次数 总次数
-------------------- ----------- -----------
TCL 1 1
康佳 2 3
联想集团 1 2

(所影响的行数为 3 行)
------解决方案--------------------
SELECT [客户名称],
[迟到次数]=COUNT(CASE WHEN ARRIVETIME <FACTIME THEN ARRIVETIME),
[总次数]=COUNT(ARRIVETIME)
FROM [表名]
GROUP BY [客户名称]

不知道对不对,反正最初的想法是这样,不知道有没有帮助
------解决方案--------------------
create table test(CustomerName varchar(20),ArriveTime varchar(10),FactTime varchar(10))
insert test select '联想集团 ', '08:00 ', '08:15 '
union all select '康佳 ', '09:00 ', '09:30 '
union all select '康佳 ', '09:00 ', '09:00 '
union all select '康佳 ', '09:00 ', '09:20 '
union all select '联想集团 ', '08:00 ', '08:00 '
union all select 'TCL ', '08:30 ', '09:00 '

select CustomerName,sum(case when ArriveTime <FactTime then 1 else 0 end) as 迟到次数,sum(1) as 总次数
from test
group by CustomerName
order by CustomerName desc

drop table test
------解决方案--------------------
select CustomerName , sum(case when FactTime> ArriveTime then 1 else 0 end) as '迟到次数 ',count(*) as