SQL将行数据与同一个表组合并连接

时间:2014-02-04 12:13:52

标签: mysql sql

我的SQL查询

SELECT emp_location, emp_system_name, emp_compName, tran_type_code, emp_morn_checkin, emp_ot_checkin, emp_ot_checkout, over_time, ontime, updated_by
FROM timesheet_tran
WHERE emp_id =  'TMSTEST'
AND tran_as_of_date =  '04/02/14'

将数据作为

返回

SQL Structure

我想找到一种合并和显示数据的方法

emp_location -- emp_system_name -- morn_check_OTM -- mor_check_DLY -- overtime_OTM --overtime_OT
AMK               ::1                8.45               8.38            1:15           6:30

我的SQL知识,不能这样做:(

2 个答案:

答案 0 :(得分:3)

您正在寻找的是 pivot 行到列中,遗憾的是MySQL没有本机数据透视表操作符,但您可以使用CASE表达式来执行此操作:

SELECT 
  emp_location, 
  emp_system_name,
  MAX(CASE WHEN tran_type_code = 'OTM' THEN emp_morn_checkin END) AS morn_check_OTM,
  MAX(CASE WHEN tran_type_code = 'DLY' THEN emp_morn_checkin END) AS morn_check_DLY,
  MAX(CASE WHEN tran_type_code = 'OT' THEN emp_morn_checkin END) AS morn_check_OT,
  MAX(CASE WHEN tran_type_code = 'OTM' THEN over_time END) AS over_time_OTM,
  MAX(CASE WHEN tran_type_code = 'DLY' THEN over_time END) AS over_time_DLY,
  MAX(CASE WHEN tran_type_code = 'OT' THEN over_time END) AS over_time_OT
FROM timesheet_tran
WHERE emp_id =  'TMSTEST'
AND tran_as_of_date =  '04/02/14'
GROUP BY emp_location, emp_system_name; 

答案 1 :(得分:0)

尝试以你想要的方式使用concat(a,' - ',b,c,d,)