MySQL在之间的语句中使用max(date)

时间:2019-02-14 06:14:48

标签: mysql max case between

感谢您的帮助。我正在尝试在CASE语句中使用max(date),但是语法不正确或??

// This works    
SELECT
     ROUND(sum(CASE WHEN Document_Date BETWEEN  DATE_FORMAT("2019-01-01", "%Y-%m-%d") AND  DATE_FORMAT("2019-01-31", "%Y-%m-%d") THEN GTotal END),0) TOTAL2019
FROM
salesdata

// But I want to use max(Document_Date) which is 2019-01-31 like so and have tried cast and different combos, but it comes out null or says invalid use of group function.  Document_Date is datetime in DB

    SELECT
         ROUND(sum(CASE WHEN Document_Date BETWEEN  DATE_FORMAT("2019-01-01", "%Y-%m-%d") AND  DATE_FORMAT(max(Document_Date), "%Y-%m-%d") THEN GTotal END),0) TOTAL2019
    FROM
    salesdata

我在做什么错-感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您正尝试将maxsum一起使用。通常,不使用子查询就无法执行此操作。

检查我的替代解决方案

SELECT
     ROUND(sum(
       CASE WHEN Document_Date BETWEEN  DATE_FORMAT("2019-01-01", "%Y-%m-%d") AND  (select max(Document_date) from salesData) THEN 
         GTotal 
       END),
     0) TOTAL2019
FROM
salesdata