mysql - 动态列别名

时间:2014-11-07 07:03:16

标签: mysql sql

嗨,我有" sql查询"查看上周每个成员完成的工作数量,以便我创建" sql查询"并且它的工作非常有意义,但我想将 week1或week2 更改为本周的数据我的" sql查询"是:

SELECT `staffID`,  
SUM(if (created_at BETWEEN NOW()-INTERVAL 1 WEEK AND NOW(), 1,0)) 
AS `week1`, 
SUM(if (created_at BETWEEN NOW()-INTERVAL 2 WEEK AND NOW()-INTERVAL 1 WEEK, 1,0)) 
AS `week2`, 
FROM tasks where status ='done'
GROUP BY `staffID

我想成为这样的" sql查询",但mysql给我错误。那么,无论如何都要解决这个问题吗?

SELECT `staffID`,  
SUM(if (created_at BETWEEN NOW()-INTERVAL 1 WEEK AND NOW(), 1,0)) 
AS NOW()-INTERVAL 1 WEEK, 
SUM(if (created_at BETWEEN NOW()-INTERVAL 2 WEEK AND NOW()-INTERVAL 1 WEEK, 1,0)) 
AS NOW()-INTERVAL 2 WEEK, 
FROM tasks where status ='done'
GROUP BY `staffID

sql给我这条消息:

1064 - 您的SQL语法出错;查看与您的MySQL服务器版本对应的手册,以便在#NOW()附近使用正确的语法 - INTERVAL 1 WEEK

2 个答案:

答案 0 :(得分:5)

答案很简单:在SQL中不可能。列别名是常量。您必须动态创建查询以实现您想要的目标:

SET @column_alias1 := NOW() - INTERVAL 1 WEEK;
SET @column_alias2 := NOW() - INTERVAL 2 WEEK;
SET @query := CONCAT('SELECT SUM(...) AS `', @column_alias1, '`, SUM(...) AS `', @column_alias2, '` FROM ...');
PREPARE dynamic_statement FROM @query;
EXECUTE dynamic_statement;

答案 1 :(得分:-1)

检查它是否有效。

为列名添加了括号。

SELECT `staffID`,  
SUM(if (created_at BETWEEN NOW()-INTERVAL 1 WEEK AND NOW(), 1,0)) 
AS (SELECT NOW()-INTERVAL 1 WEEK), 
SUM(if (created_at BETWEEN NOW()-INTERVAL 2 WEEK AND NOW()-INTERVAL 1 WEEK, 1,0)) 
AS (SELECT  NOW()-INTERVAL 2 WEEK), 
FROM tasks where status ='done'
GROUP BY `staffID