我的 SQL 查询运行完美,但是当我添加 CTE 函数时,出现错误

My SQL query runs perfectly, but when I add the CTE function, I get an error

我的 SQL 查询运行完美,但是当我添加 CTE 函数时,出现错误 请检查此代码并让我知道 CTE 有什么问题:

WITH Consumption_details(UnitId, consumption, monthof, yearof) AS
(
    SELECT 
        UnitId, SUM(consumption) AS consumption, 
        monthof, yearof  
    FROM 
        (SELECT 
             UnitId, apartment_consumption, 
             DATEPART(MONTH, day) AS monthof, 
             DATEPART(YEAR,day) AS yearof 
         FROM 
             MeterReading) AS t
    GROUP BY 
        yearof, monthof, UnitId
    HAVING 
        monthof = 2 AND yearof = 2022
    ORDER BY
        UnitID
) 

你不能在 CTE 中包含 ORDER BY(除非你还包含 TOP,在这种情况下你不应该这样做),你需要 CTE 的一些东西 - 它只是一个表达式,而不是一个查询。

;;;/*be safe!*/;;;With cd(SonnenUnitId, consumption, monthof, yearof) AS
    (
        SELECT SonnenUnitId, ...
        ...
        GROUP BY yearof, monthof, SonnenUnitId
        HAVING monthof =2 and yearof =2022
    )
SELECT * FROM cd Order by SonnenUnitID;

顺便说一句,这个查询可能 整体 更高效,不需要 CTE and 子查询,任何HAVING,并且扫描可能成为搜索。

DECLARE @mo int = 2, @yo int = 2022;


DECLARE @m date = DATEFROMPARTS(@yo, @mo, 1);

SELECT SonnenUnitId, 
  SUM(apartment_consumption) AS consumption, 
  monthof = @mo, 
  yearof = @yo  
FROM dbo.SonnenMeterReading
  WHERE [day] >= @m 
    AND [day] < DATEADD(MONTH, 1, @m)
  GROUP BY SonnenUnitId
  ORDER BY SonnenUnitId;