2016-01-06 33 views
1

我有以下表格: enter image description here计算各行整体总列与动态SQL语句表

而且我想查询一个表来显示基于位置的付款总额(有动态值)为每一位用户+整体总如下: enter image description here

我能得到它的闯入位置点,我不能唯一得到的是总列,这是我的SQL:

USE fypdb; 
SET @sql = NULL; 

SELECT GROUP_CONCAT(
    DISTINCT CONCAT('SUM(CASE WHEN attendance.location_id=''', attendance.location_id,''' then 
    FORMAT(position.pay_rate*TIME_TO_SEC(TIMEDIFF(attendance.logout_time, attendance.login_time))/3600, 2) else 0 end) AS `', 
    location.name,'`') 
) INTO @sql FROM attendance JOIN location ON attendance.location_id = location.location_id; 

SET @sql = CONCAT('SELECT user.user_name,', @sql, ' 
       SUM(FORMAT(position.pay_rate*TIME_TO_SEC(TIMEDIFF(attendance.logout_time, attendance.login_time))/3600, 2)) AS Total ',  #this is the problematic attribute 
       'FROM attendance 
       JOIN user ON attendance.user_id = user.user_id 
       JOIN position ON user.position_id = position.position_id 
        GROUP BY attendance.user_id'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

按照上面,如果我删除有问题的属性(总)的命令工作正常,但是当我试图让我总共收到以下错误:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SUM(FORMAT(position.pay_rate*TIME_TO_SEC(TIMEDIFF(attendance.logout_time, attend' at line 4 

谁能告诉我我在做什么错?非常感谢你!

注:我使用的MySQL版本5.7.9

回答

0

,我可以看到你使用级联和你是在有问题的共线后失踪的空间。下一行'FROM没有空格,所以产生的查询是 AS TotalFROM而不是AS Total FROM

+0

这是正确的,我修改了,但错误仍然是相同的。 –