SQL Server Row_number超过了订单,导致列名无效

时间:2017-08-17 10:26:50

标签: sql-server

我有一张这样的表:

fld_Id ... ... ... ... ... ... fld_ConsDateTime ... ... ...
-----------------------------------------------------------
1                             2017-01-01 00:00:00.000 
2                             2017-01-02 00:00:00.000
... ... ... .. ..... .. .. . . . .....................

等等..我生成一个这样的查询,并按预期完美地运行

SELECT 
    CAST(DATEADD(MINUTE, fld_TZAM - 180 , fld_ConsDateTime) AS DATE) AS fld_ConsDate, 
    SUM(fld_EnergyTotalIndexValue) AS fld_ConsumptionValue , 
    MIN(fld_ConsDateTime) AS fld_ConsStartDateTime , 
    MAX(fld_ConsDateTime) AS fld_ConsEndDateTime , 
    MAX(fld_Id) AS fld_Id   
FROM 
    tbl_EM_DeviceEnergyHourlyConsumption  
WHERE
    fld_ConsDateTime >= DATEADD(MINUTE, -1*(fld_TZAM) + 180, N'2017-07-18 00:00:00') AND 
    fld_ConsDateTime < DATEADD(MINUTE, -1*(fld_TZAM) + 180, N'2017-08-17 00:00:00')
GROUP BY 
    CAST(DATEADD(MINUTE, fld_TZAM - 180 , fld_ConsDateTime) AS DATE)

在浏览器中,用户可以单击某个字段并对记录进行排序。用户单击我生成的查询(我只包括ROW_NUMBER() OVER (ORDER BY fld_ConsDate asc) AS RN)后填充错误

  

列名称无效&#39; fld_ConsDate&#39;

我的代码:

SELECT 
    CAST(DATEADD(MINUTE, fld_TZAM - 180, fld_ConsDateTime) AS DATE) AS fld_ConsDate, 
    SUM(fld_EnergyTotalIndexValue) AS fld_ConsumptionValue, 
    MIN(fld_ConsDateTime) AS fld_ConsStartDateTime, 
    MAX(fld_ConsDateTime) AS fld_ConsEndDateTime, 
    MAX(fld_Id) AS fld_Id,
    ROW_NUMBER() OVER (ORDER BY fld_ConsDate ASC) AS RN
FROM
    tbl_EM_DeviceEnergyHourlyConsumption  
WHERE
    fld_ConsDateTime >= DATEADD(MINUTE, -1*(fld_TZAM) + 180, N'2017-07-18 00:00:00') AND 
    fld_ConsDateTime < DATEADD(MINUTE, -1*(fld_TZAM) + 180, N'2017-08-17 00:00:00')
GROUP BY 
    CAST(DATEADD(MINUTE, fld_TZAM - 180 , fld_ConsDateTime) AS DATE)

似乎有什么问题?有什么提示吗?

0 个答案:

没有答案