如何根据子查询结果聚合数据

时间:2016-11-15 18:07:44

标签: sql-server

我有一个像这样的SQL查询:

SELECT (SUM(DURATIONSECS) / 3600.00) AS LaborHrs, 
(SELECT LABORLEV2 t2 FROM LABOR WHERE LABORID = t1.LABORID) As Dept
FROM Table1 t1 
WHERE DTM BETWEEN 'datetime1' AND 'datetime2' AND 
(SELECT LABORLEV1 FROM LABOR WHERE LABORID = t1.LABORID) = '100' 
AND PAYCODEID='1'
Group BY LABORID

这给了我正确的数据:

LaborHrs        Dept
90.5000000      office
1033.2500000    retail
522.2500000     retail
217.5000000     misc
1145.5000000    misc
40.0000000      retail

但是,如果dept名称相同,我需要汇总结果,例如我需要将“retail”和“misc”的所有工时的总和放在同一列中。我尝试过Dept的分组,但它没有识别出列名。

2 个答案:

答案 0 :(得分:3)

我根据我对你的问题的理解重写了你的查询,但我对这一部分非常怀疑:

DTM BETWEEN 'datetime1' AND 'datetime2'

我认为它是您要替换的日期时间变量或数字。 如果是这种情况,我猜这里可能就是答案。

SELECT (SUM(DURATIONSECS) / 3600.00) AS LaborHrs, 
    , l1.LABORLEV2 AS Dept
FROM Table1 t1 
    JOIN LABOR l1 ON l1 ON l1.LABORID=t1.LABORID
WHERE DTM BETWEEN 'datetime1' AND 'datetime2' AND l1.LABORLEV1='100'
    AND t1.PAYCODEID='1'
Group BY t1.LABORID, l1.LABORLEV2

答案 1 :(得分:1)

如果要对某些列进行分组,则该列不能是子选择,因此您必须使用JOINS重写查询。

通过我对您的查询的理解,您可以加入表Tabl1和LABOR并将您的条件移动到单个WHERE语句,如下所示:

SELECT 
    l.LABORLEV2 AS Dept,
    (SUM(t1.DURATIONSECS) / 3600.00) AS LaborHrs
FROM Table1 t
INNER JOIN LABOR l ON t.LABORID=l.LABORID
WHERE 
    l.LABORLEV1='100' AND
    t1.PAYCODEID='1' AND
    t1.DTM BETWEEN 'datetime1' AND 'datetime2'
GROUP BY l.LABORLEV2