2016-01-06 32 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

這是正確的,我修改了,但錯誤仍然是相同的。 –