--創建測試環境
Create Table TEST(CustomerName Nvarchar(10), ArriveTime Varchar(5), FactTime Varchar(5))
--插入數據
Insert Into TEST
Select N'联想集团', '08:00', '08:15' Union All
Select N'康佳', '09:00', '09:30' Union All
Select N'康佳', '09:00', '09:00' Union All
Select N'康佳', '09:00', '09:20' Union All
Select N'联想集团', '08:00', '08:00' Union All
Select N'TCL', '08:30', '09:00'
GO
--測試
Select
CustomerName,
SUM(Case When ArriveTime < FactTime Then 1 Else 0 End) As 迟到次数,
Count(*) As 总次数
From
TEST
Group By
CustomerName
GO
--刪除測試環境
Drop Table TEST
--結果
/*
CustomerName 迟到次数 总次数
TCL 1 1
康佳 2 3
联想集团 1 2
*/
借用一下上面创建的表 语句如下
===================
select a.customerName as 客户名称,sum(a.flat) as 迟到次数 ,count(customerName) as 总次数 from
(select customerName,case when arrivetime<facttime then 1 else 0 end as flat
from yourtable) as a
group by a.customerName
==================
我解释一下语句
select customerName,case when arrivetime<facttime then 1 else 0 end as flat
from yourtable
得出每条记录得迟到情况 迟到为1 否则为0
修改一下:
select customerName, count(1) as late, (select count(1) from yourtable where customerName = x.customerName group by customerName) as total
from yourtable x
where arrivetime < facttime
group by customerName
insert into yourtable
select N'联想集团', '08:00' ,'08:15' union all
select N'康佳' , '09:00' ,'09:30' union all
select N'康佳' , '09:00' ,'09:00' union all
select N'康佳' , '09:00' ,'09:20' union all
select N'联想集团' , '08:00' ,'08:00' union all
select N'TCL', '08:30', '09:00'
select x.customerName, x.late, y.total
from
(
select customerName, count(1) as late
from
(
select *
from yourtable
where arrivetime < facttime
) a
group by customerName
) x
inner join
(
select customerName, count(1) as total
from yourtable
group by customerName
) y
on x.customerName = y.customerName
select x.customerName, x.late, y.total
from
(
select customerName, count(1) as late
from
(
select *
from yourtable
where arrivetime < facttime
) a
group by customerName
) x
inner join
(
select customerName, count(1) as total
from yourtable
group by customerName
) y
on x.customerName = y.customerName