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

求一统计sql语句!
从一个表中统计出每天没台终端的开关机状态。
表中主要包括:终端编号(mobile),(lasttime)时间,(runstatus)终端状态
等字段   ,无主键。
终端状态每天记录4次,即lasttime   记录同一天的四个时间段(如2007-8-24   08:45)。状态有三种(0   正常,2   数据无效,1   关机),其中,0和2   都算是开机,每天的四个时间段中有一次开机,这一天算是开机,四次都关机,算是关机。
要求统计出,一个时间段内每天没台终端的开关机状态。

我用以下语句,估且能统计出开机状态,但关机状态不知道如何实现。
请各位多多指点!
select   distinct     top   100   mobile   ,substring(lasttime,1,10)   as   lasttime,certid,groupid,   '开机 '   as   status     from   ZZMON..T_selftest     where   1=1  
and   lasttime> = '2007-08-01 '   and   lasttime <= '2007-08-30 '       group   by  
mobile,substring(lasttime,1,10),certid,runstatus,groupid
        having   runstatus= '0 '   or   runstatus= '2 '  


------解决方案--------------------
select distinct * from
(
select id,name,cardid,convert(varchar(10),time,120) time , status = '没来 ' from tb where id not in
(
select id,name,cardid,convert(varchar(10),time,120) time , status = '来 ' from tb where status = '来 ' or status = '迟到 '
) t
union all
select id,name,cardid,convert(varchar(10),time,120) time , status = '来 ' from tb where status = '来 ' or status = '迟到 '
) m
order by id,name, time
------解决方案--------------------
select mobile,convert(char(10),lasttime,112),
case when min(runstatus) <> 0 and max(runstatus) <> 2 then '关 '
when min(runstatus)=0 then '开 '
else '其它 '
end
from @a a
group by mobile,convert(char(10),lasttime,112)
------解决方案--------------------
create table tb(id int, name varchar(10) , cardid varchar(10),time datetime,status varchar(10))

insert into tb values(1, '111 ', '111 ', '2007-8-15 08:00:22 ', '来 ')
insert into tb values(1, '111 ', '111 ', '2007-8-15 13:30:22 ', '迟到 ')
insert into tb values(2, '222 ', '222 ', '2007-8-15 08:00:22 ', '没来 ')
insert into tb values(2, '222 ', '222 ', '2007-8-15 13:30:22 ', '没来 ')
insert into tb values(3, '111 ', '111 ', '2007-8-15 08:00:22 ', '没来 ')
insert into tb values(3, '333 ', '333 ', '2007-8-15 13:30:22 ', '来 ')

select distinct * from
(
select id,name,cardid,convert(varchar(10),time,120) time , status = '没来 ' from tb where id not in
(
select id from tb where status = '来 ' or status = '迟到 '
)
union all
select id,name,cardid,convert(varchar(10),time,120) time , status = '来 ' from tb where status = '来 ' or status = '迟到 '
) m
order by id,name, time
drop table tb

/*
id name cardid time status
----------- ---------- ---------- ---------- ------
1 111 111 2007-08-15 来
2 222 222 2007-08-15 没来
3 333 333 2007-08-15 来

(所影响的行数为 3 行)

*/