MySQL Extract函数提供语法错误

时间:2014-02-12 11:10:01

标签: mysql date

我在订单表上运行查询,以计算每个用户在6个月前的任何一天(例如: - 2013年8月)发出的总请求数。

这样可行: -

SELECT userid,firstname,surname,sum(IF(MONTH(date_placed) = MONTH(DATE_SUB(CURDATE(), INTERVAL 6 MONTH)) and YEAR(date_placed) = YEAR(DATE_SUB(CURDATE(), INTERVAL 6 MONTH)), 1,0))
FROM requests 
WHERE homelib='SBC'
GROUP BY userid
ORDER BY surname;

但是这会因SQL语法错误而失败: -

SELECT userid,firstname,surname,sum(IF(EXTRACT(YEAR_MONTH FROM date_placed) = EXTRACT(YEAR_MONTH FROM DATE_SUB(CURDATE(), INTERVAL 6 MONTH)), 1,0))
FROM requests 
WHERE homelib='SBC'
GROUP BY userid
ORDER BY surname;

是否有更高效的SQL语句来执行此操作? 类似的东西:

 YEAR_MONTH(date_placed) = YEAR_MONTH(DATE_SUB(CURDATE(), INTERVAL 6 MONTH))

它必须只查看6个月前的任何一天的订单(例如: - 2013年8月期间),并在运行查询时从6个月前动态计算。

1 个答案:

答案 0 :(得分:0)

据我所知,EXTRACT不适用于日期算术。我不确定我的方法,但你可以尝试一下。这是查询:

SELECT userid, firstname, surname, sum(IF(date_format(date_placed,"%y-%m") = date_format(DATE_SUB(CURDATE(), INTERVAL 6 MONTH), "%y-%m"), 1,0)) FROM requests WHERE homelib='SBC' GROUP BY userid ORDER BY surname;