使用CASE和GROUP BY

时间:2014-02-18 11:58:15

标签: tsql group-by case

我在T-SQL中有以下查询:

SELECT dbo.table2.device, 
    dbo.table2.CREATETIME AS create_time,
    CASE WHEN dbo.table1.ACTIONID = 1 
        THEN dbo.table1.startstop 
    END AS start_time,
    CASE WHEN dbo.table1.ACTIONID  = 2 
        THEN dbo.table1.startstop 
    END AS stop_time,
    dbo.table2.collect_time
FROM dbo.table2
JOIN dbo.table1 ON dbo.table1.CREATETIME = dbo.table2.CREATETIME;

...它给了我一个包含多行的结果表,每一行都有一次启动 - 一次是结束时间(sql时间 - 为简单起见缩短) - 另一行是NULL - 例如:

device | create_time | start_time | stop_time | collect_time
1      | 0000001     | 0000001    | NULL      | 0000001
1      | 0000001     | NULL       | 0000002   | 0000001

我想将这两行分组(使用create_time作为ID),所以我将它们合并为一个....谢谢!

2 个答案:

答案 0 :(得分:2)

您可以汇总(SUM)这些列:

SELECT dbo.table2.device, 
    dbo.table2.CREATETIME AS create_time,
    SUM(CASE WHEN dbo.table1.ACTIONID = 1 
        THEN dbo.table1.startstop ELSE 0
    END) AS start_time,
    SUM(CASE WHEN dbo.table1.ACTIONID  = 2 
        THEN dbo.table1.startstop ELSE 0
    END) AS stop_time,
    dbo.table2.collect_time
FROM dbo.table2
JOIN dbo.table1 ON dbo.table1.CREATETIME = dbo.table2.CREATETIME
GROUP BY dbo.table2.device, dbo.table2.CREATETIME, dbo.table2.collect_time;

答案 1 :(得分:0)

另外我认为使用子查询也可以解决问题

SELECT
X.Device
,sum(X.start_time)
,sum(X.stop_time)
,X.collect_time
from(
SELECT dbo.table2.device, 
    dbo.table2.CREATETIME AS create_time,
    CASE WHEN dbo.table1.ACTIONID = 1 
        THEN dbo.table1.startstop 
    END AS start_time,
    CASE WHEN dbo.table1.ACTIONID  = 2 
        THEN dbo.table1.startstop 
    END AS stop_time,
    dbo.table2.collect_time
FROM dbo.table2
JOIN dbo.table1 ON dbo.table1.CREATETIME = dbo.table2.CREATETIME) AS X
group by
X.Device, X.collect_time