SQL add sum to existing query(无法对包含聚合或子查询的表达式执行聚合函数。)

时间:2013-10-28 05:27:45

标签: sql sql-server group-by

我有一个现有的工作SQL查询我想现在GroupBy但是收到错误:无法对包含聚合或子查询的表达式执行聚合函数。

我的情景说明:

我的主表(dbo.DataLog)包含3列, TimestampUTC,MeterTagId,Data

数据通常每隔15分钟进行一次,我每个都有很多米( MeterTagId TimestampUTC Data 列是一个浮点数,这是一个累计值。即,为了获得一个仪表周期的实际值,我需要从当前值中减去最后一个值。在此之前我已经成功地查询了单个仪表,但现在我正在尝试按时间分组并显示当时所有仪表的总和/总和。

原始工作非求和查询

 SELECT
    l.TimestampUTC
    -- Get this value minus the last value
    ,(SELECT  (l.[Data] - 
                (   SELECT TOP 1 l2.Data
                    FROM [DataLog] l2
                    WHERE l2.MeterTagId = l.MeterTagId
                    AND l2.TimestampUTC < l.TimestampUTC
                    ORDER BY l2.TimestampUTC DESC)
                )
        ) AS Actual_Value
    FROM [dbo].[DataLog] l
    INNER JOIN [dbo].MeterTags t on t.MeterTagId = l.MeterTagId
    INNER JOIN [dbo].Meters m on m.MeterId = t.MeterId
    INNER JOIN [dbo].GroupsMeters gm on gm.MeterId = m.MeterId
    INNER JOIN [dbo].Groups g on g.GroupId = gm.GroupId
    LEFT OUTER JOIN dbo.Units u on u.UnitId = t.UnitId
    WHERE (@MeterId is null OR M.MeterId in (@MeterId))
    AND (@MeterTagId is null OR t.MeterTagId in (@MeterTagId))
    AND (@StartDate is null OR l.TimestampUTC >= @StartDate)
    AND (@EndDate is null OR l.TimestampUTC <= @EndDate)
    AND (@GroupId is null OR g.GroupId in (@GroupId))

我尝试获取摘要:

 SELECT
    l.TimestampUTC
    -- Get this value minus the last value
    ,   (SELECT  SUM(l.[Data] - 
                (   SELECT TOP 1 l2.Data
                    FROM [DataLog] l2
                    WHERE l2.MeterTagId = l.MeterTagId
                    AND l2.TimestampUTC < l.TimestampUTC
                    ORDER BY l2.TimestampUTC DESC)
                )
        )AS Actual_Value
    FROM [dbo].[DataLog] l
    INNER JOIN [dbo].MeterTags t on t.MeterTagId = l.MeterTagId
    INNER JOIN [dbo].Meters m on m.MeterId = t.MeterId
    INNER JOIN [dbo].GroupsMeters gm on gm.MeterId = m.MeterId
    INNER JOIN [dbo].Groups g on g.GroupId = gm.GroupId
    LEFT OUTER JOIN dbo.Units u on u.UnitId = t.UnitId
    WHERE (@MeterId is null OR M.MeterId in (@MeterId))
    AND (@MeterTagId is null OR t.MeterTagId in (@MeterTagId))
    AND (@StartDate is null OR l.TimestampUTC >= @StartDate)
    AND (@EndDate is null OR l.TimestampUTC <= @EndDate)
    AND (@GroupId is null OR g.GroupId in (@GroupId))
    AND t.Name ='Real Energy Net'
    GROUP BY l.TimestampUTC

我已经在这里阅读了其他帖子,但无法理解所需的逻辑,我想/希望这是sql dev经常遇到的事情?谢谢!

1 个答案:

答案 0 :(得分:1)

好的,我把它解决了,真的很简单。希望这个解释可以帮助其他人在将来遇到同样的问题。

SELECT 
    myTable.TimestampUTC
    , SUM(myTable.Actual_Value) as [Actual Value]
FROM
(
--My original query
) AS myTable

GROUP BY myTable.TimestampUTC