http://community.csdn.net/Expert/topic/5073/5073353.xml?temp=3.689212E-02

解决方案 »

  1.   

    --SET Language English
    --SET Language 繁體中文
    --SET Language 简体中文Create Table TEST
    (id varchar(10),
     MATHINENO varchar(10),
     MSGTYPE int,
     WORKTIME datetime)
    Insert TEST Select '001',           '001',                   0,                          '2007-3-21 7:41:39'
    Union All Select '002',           '001',                   1,                          '2007-3-21 9:41:39' 
    Union All Select '003',           '001',                   0,                         '2007-3-21 11:41:39'
    Union All Select '004',           '001',                   1,                           '2007-3-21 12:41:39'
    Union All Select '005',           '001',                   0,                            '2007-3-21 15:41:39'
    Union All Select '006',           '001',                   1,                             '2007-3-21 20:41:39'
    Union All Select '007',           '001',                   0,                          '2007-3-22 8:41:39'
    Union All Select '008',           '001',                   1,                         '2007-3-22 9:41:39'
    Union All Select '009',           '001',                   0,                         '2007-3-22 11:41:39'
    Union All Select '010',           '001',                   1,                           '2007-3-22 12:41:39'
    Union All Select '011',           '001',                   0,                            '2007-3-22 15:41:39'
    Union All Select '012',           '001',                   1,                             '2007-3-22 19:41:39' 
    GO
    --Select * From TEST
    Select 
    MATHINENO,
    Convert(Varchar, 第一次点火时间, 120) + (Case When DatePart(Hour, 第一次点火时间) < 8 Then N'(正常)' Else N'(不正常)' End) As 第一次点火时间,
    Convert(Varchar, 最后一次熄火时间, 120) + (Case When DatePart(Hour, 最后一次熄火时间) >= 20 Then N'(正常)' Else N'(不正常)' End) As 最后一次熄火时间,
    WORKTIME
    From
    (
    Select 
    MATHINENO,
    Min(Case MSGTYPE When 0 Then WORKTIME Else Null End) As 第一次点火时间,
    Max(Case MSGTYPE When 1 Then WORKTIME Else Null End) As 最后一次熄火时间,
    Convert(Varchar(10), WORKTIME, 120) As WORKTIME
    From
    TEST
    Group By 
    MATHINENO,
    Convert(Varchar(10), WORKTIME, 120)
    ) A
    GO
    Drop Table TEST
    GO
    /*
    MATHINENO 第一次点火时间 最后一次熄火时间 WORKTIME
    001 2007-03-21 07:41:39(正常) 2007-03-21 20:41:39(正常) 2007-03-21
    001 2007-03-22 08:41:39(不正常) 2007-03-22 19:41:39(不正常) 2007-03-22
    */