0

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

我的场景的解释:

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

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

原始工作非求和查询:

 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 经常遇到的事情?谢谢!

4

1 回答 1

1

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

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

GROUP BY myTable.TimestampUTC
于 2013-10-28T05:49:34.960 回答