从多行事件中获取最小值和最大值

时间:2014-11-24 14:05:13

标签: sql

我的桌子结构如下:

ID      TIME_UNIX     STATUS      TIME_DDMMYY_HHMMSS
1       1416234308      1         (dateadd(second,[time],'19700101'))
1       1416234313      0         (dateadd(second,[time],'19700101'))
1       1416234319      1         (dateadd(second,[time],'19700101'))
1       1416234337      0         (dateadd(second,[time],'19700101'))
2       1416319268      1         (dateadd(second,[time],'19700101'))  
2       1416319280      0         (dateadd(second,[time],'19700101'))
2       1416319631      1         (dateadd(second,[time],'19700101'))

价值描述

ID is the identifier of the object who does the insert
TIME_UNIX is when it happened
Status can be 1 or 0 (enable/disable)
TIME_DDMMYY_HHMMSS is just a friendly view of TIME_UNIX column

所以,我尝试做的是生成一个视图,向每个对象显示每个事件的最小和最大小时数,这意味着,首先启用和最后一次按对象禁用

ID    FIRST_ENABLE_TIME    LAST_DISABLE_TIME    DDMMYYY
1     1416234308           1416234337           17Nov2014
2     1416319268           1416319280           17Nov2014

一直尝试很多内部联接,观点到目前为止还没有运气......

任何人都可以帮我这个吗? 提前致谢

3 个答案:

答案 0 :(得分:1)

SELECT ID, 
    MIN(CASE WHEN STATUS = 1 THEN TIME_UNIX ELSE NULL END) AS FIRST_ENABLE_TIME, 
    MAX(CASE WHEN STATUS = 0 THEN TIME_UNIX ELSE NULL END) AS LAST_DISABLE_TIME,
    TIME_DDMMYY_HHMMSS AS DDMMYYY
FROM MyTable
GROUP BY ID, TIME_DDMMYY_HHMMSS

答案 1 :(得分:1)

SELECT ID, 
    MIN(CASE WHEN STATUS = 1 THEN TIME_UNIX ELSE NULL END) AS FIRST_ENABLE_TIME, 
    MAX(CASE WHEN STATUS = 0 THEN TIME_UNIX ELSE NULL END) AS LAST_DISABLE_TIME,
    convert(varchar(10),TIME_DDMMYY_HHMMSS,103) AS DDMMYYY FROM
FROM MyTable
GROUP BY ID, convert(varchar(10),TIME_DDMMYY_HHMMSS,103)

答案 2 :(得分:0)

SELECT ID, 
       (SELECT MIN(TIME_UNIX) 
        FROM table 
        WHERE status = 1) AS FIRST_ENABLE_TIME, 
       (SELECT MAX(TIME_UNIX)
        FROM table 
        WHERE status = 0) AS LAST_DISABLE_TIME, 
       TIME_DDMMYY_HHMMSS AS DDMMYYY
FROM table
GROUP BY ID, TIME_DDMMYY_HHMMSS