在模式

时间:2017-03-06 11:43:13

标签: mysql sql

我遇到一个问题,我无法使 WEEK(日期,模式)功能正常工作。

我有一个SQL,我按年度分组总和,然后按周分组:

SELECT SUM(o.total) as total_org, SUM(o.total_eur) as total_eur, 
WEEK(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)) as period, YEAR(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)) as smallerperiod, `s`.`domain`
FROM `orders` `o`
JOIN `shops` `s` ON `o`.`domain_id` = `s`.`id`
WHERE `o`.`domain_id` = '5'
GROUP BY YEAR(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)), WEEK(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR))
ORDER BY `smallerperiod` ASC, `period` ASC

哪个完全符合我的要求,除了从0开始的周数。我发现对我来说效果最好的模式是3号,所以我尝试将我的SQL更改为:

SELECT SUM(o.total) as total_org, SUM(o.total_eur) as total_eur, 
WEEK('DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)', 3) as period, YEAR(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)) as smallerperiod, `s`.`domain`
FROM `orders` `o`
JOIN `shops` `s` ON `o`.`domain_id` = `s`.`id`
WHERE `o`.`domain_id` = '5'
GROUP BY YEAR(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)), WEEK('DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)', 3))
ORDER BY `smallerperiod` ASC, `period` ASC

然而它只是给了我错误

  

您的SQL语法有错误;查看与MariaDB服务器版本对应的手册,以获取正确的语法   靠近')ORDER BY smallerperiod ASC,period ASC

编辑: 我试图让它在没有单引号的情况下工作:

SELECT SUM(o.total) as total_org, SUM(o.total_eur) as total_eur, 
WEEK(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR), 3) as period, YEAR(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)) as smallerperiod, `s`.`domain`
FROM `orders` `o`
JOIN `shops` `s` ON `o`.`domain_id` = `s`.`id`
WHERE `o`.`domain_id` = '5'
GROUP BY YEAR(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)), WEEK(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR), 3))
ORDER BY `smallerperiod` ASC, `period` ASC

但是,它会返回相同的错误

2 个答案:

答案 0 :(得分:1)

您必须删除单引号arround 'DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)',因为您要调用函数而不是将其用作字符串。

你得到了theeroor,因为你在这里有一个额外的括号:HOUR)', 3))

所以查询必须是:

SELECT SUM(o.total) as total_org, SUM(o.total_eur) as total_eur, 
WEEK(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR), 3) as period, YEAR(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)) as smallerperiod, `s`.`domain`
FROM `orders` `o`
JOIN `shops` `s` ON `o`.`domain_id` = `s`.`id`
WHERE `o`.`domain_id` = '5'
GROUP BY YEAR(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR)), WEEK(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR), 3)
ORDER BY `smallerperiod` ASC, `period` ASC

答案 1 :(得分:0)

你只需要在getContext()之后移除最后一个括号。否则,我已经尝试了相同的完美性。 您也可以尝试下面的代码。

WEEK(DATE_ADD(o.date_created_utc, INTERVAL 0 HOUR), 3))