DATEADD关键字' AS'附近的语法不正确

时间:2017-08-03 13:21:29

标签: sql-server

以下查询在DATEADD部分中给出了错误,我似乎无法在此处看到问题或语法错误。关于我的错误的任何提示?

SELECT 
    YEAR(DATEADD(MINUTE, 180 - 480, fld_ConsDateTime) AS DATE) AS fld_year, 
    MONTH(DATEADD(MINUTE, 180 - 480, fld_ConsDateTime) AS DATE) AS fld_month, 
    fld_DeviceId, 
    SUM(fld_EnergyTotalIndexValue) AS Total_Monthly_Consumption,
    MIN(fld_ConsDateTime) AS Min_ConsDateTime, 
    MAX(fld_ConsDateTime) AS Max_ConstDateTime
FROM tbl_EM_DeviceEnergyHourlyConsumption
WHERE
    fld_Deleted = 0
    AND fld_DeviceId = 5
    AND fld_ConsDateTime >= DATEADD(MINUTE, -180 + 480, '2017-01-01 00:00')
    AND fld_ConsDateTime <  DATEADD(MINUTE, -180 + 480, '2017-08-01 00:00')
GROUP BY YEAR(DATEADD(MINUTE, 180 - 480, fld_ConsDateTime) AS DATE), MONTH(DATEADD(MINUTE, 180 - 480, fld_ConsDateTime) AS DATE), fld_DeviceId

ORDER BY fld_month ASC

PS:错误消息:关键字&#39; AS&#39;附近的语法不正确。

2 个答案:

答案 0 :(得分:4)

你不应该在 4个地方AS DATE。这是一个更正版本:

SELECT 
    YEAR(DATEADD(MINUTE, 180 - 480, fld_ConsDateTime)) AS fld_year, 
    MONTH(DATEADD(MINUTE, 180 - 480, fld_ConsDateTime)) AS fld_month, 
    fld_DeviceId, 
    SUM(fld_EnergyTotalIndexValue) AS Total_Monthly_Consumption,
    MIN(fld_ConsDateTime) AS Min_ConsDateTime, 
    MAX(fld_ConsDateTime) AS Max_ConstDateTime
FROM tbl_EM_DeviceEnergyHourlyConsumption
WHERE
    fld_Deleted = 0
    AND fld_DeviceId = 5
    AND fld_ConsDateTime >= DATEADD(MINUTE, -180 + 480, '2017-01-01 00:00')
    AND fld_ConsDateTime <  DATEADD(MINUTE, -180 + 480, '2017-08-01 00:00')
GROUP BY YEAR(DATEADD(MINUTE, 180 - 480, fld_ConsDateTime)), MONTH(DATEADD(MINUTE, 180 - 480, fld_ConsDateTime)), fld_DeviceId

ORDER BY fld_month ASC

答案 1 :(得分:0)

GROUP BY子句不允许使用别名。另外,不要将别名嵌套在SELECT中。请参阅下面的简要示例,了解您无法做到的事情。

DECLARE @Table TABLE (ID INT)
SELECT ID,COUNT(*) FROM @Table GROUP BY ID --Works
SELECT ID AS TEST,COUNT(*) FROM @Table GROUP BY ID --Works
SELECT (ID AS TEST) AS [ThisWillBreak],COUNT(*) FROM @Table GROUP BY ID
SELECT ID,COUNT(*) FROM @Table GROUP BY ID AS [ThisWillBreak]