查询SQL Server的总和

时间:2019-04-11 13:07:25

标签: sql sql-server

我需要添加另一个查询的结果,但是我不能

图像中是第一个查询的结果。 现在,我需要添加此结果并按日期分组

Example in Image

示例:   200 + 200 + 199 + 199 + 199 + 200 .... =结果

我的代码:

 SELECT SUM (
(SELECT 
    [DATA],
    IIF((
            Icas.CONTADOR_ICAS_1 - COALESCE(LAG(Icas.CONTADOR_ICAS_1) OVER (ORDER BY Icas.COD_ICAS), 0)) > 0 
            AND (Icas.CONTADOR_ICAS_1 - COALESCE(LAG(Icas.CONTADOR_ICAS_1) OVER ( ORDER BY Icas.COD_ICAS),0)) < 500, 
            (Icas.CONTADOR_ICAS_1 - COALESCE(LAG(Icas.CONTADOR_ICAS_1) OVER (ORDER BY Icas.COD_ICAS), 0)), 0) AS DifL1
    FROM VW_ICAS Icas )) AS Res
FROM
    VW_ICAS
GROUP BY
    [DATA]

Result of my query

2 个答案:

答案 0 :(得分:0)

您在列而不是结果上进行汇总。您的解决方案可以采用2种不同的方式。一种是聚合数据

SELECT 
    [DATA],
    SUM (IIF((
            Icas.CONTADOR_ICAS_1 - COALESCE(LAG(Icas.CONTADOR_ICAS_1) OVER (ORDER BY Icas.COD_ICAS), 0)) > 0 
            AND (Icas.CONTADOR_ICAS_1 - COALESCE(LAG(Icas.CONTADOR_ICAS_1) OVER ( ORDER BY Icas.COD_ICAS),0)) < 500, 
            (Icas.CONTADOR_ICAS_1 - COALESCE(LAG(Icas.CONTADOR_ICAS_1) OVER (ORDER BY Icas.COD_ICAS), 0)), 0)) AS DifL1
FROM VW_ICAS Icas 
GROUP BY [DATA];

或者您可以通过将结果集转换为派生表而简单地获取结果集中所有行的SUM,但仍引用列。

SELECT SUM(DifL1) AS SUMDifL1
FROM(
    SELECT 
        [DATA],
        IIF((
                Icas.CONTADOR_ICAS_1 - COALESCE(LAG(Icas.CONTADOR_ICAS_1) OVER (ORDER BY Icas.COD_ICAS), 0)) > 0 
                AND (Icas.CONTADOR_ICAS_1 - COALESCE(LAG(Icas.CONTADOR_ICAS_1) OVER ( ORDER BY Icas.COD_ICAS),0)) < 500, 
                (Icas.CONTADOR_ICAS_1 - COALESCE(LAG(Icas.CONTADOR_ICAS_1) OVER (ORDER BY Icas.COD_ICAS), 0)), 0) AS DifL1
    FROM VW_ICAS Icas )x;

答案 1 :(得分:0)

我想这个查询会给出您在图像中提供的数据:

SELECT [DATA], IIF(...) AS DifL1
FROM VW_ICAS Icas

(为清楚起见,我将DifL1的表达式截短了。)

您要使用该数据执行此操作:

SELECT [DATA], SUM(DifL1)
FROM [the result above]
GROUP BY [DATA]

您可以将第一个查询作为表表达式放入第二个查询:

SELECT [DATA], SUM(DifL1)
FROM (SELECT [DATA], IIF(...) AS DifL1
      FROM VW_ICAS Icas) AS X
GROUP BY [DATA]

我想这应该有用。

这是@LuisCazares答案的第二个查询的变体,但对字段[DATA]进行了分组。