简体   繁体   中英

Split mysql row into 2 rows based on 2 column values

I am trying to create an output view of timecard data so it can be exported to a payroll system. Currently, the data structure is like this.

|Emp_ID|Date|Job|CostCode|Reg_Hrs|OT_Hrs|
Data
|BR0000|date|012|01234567|0000008|000002|

The import process requires Regular hours and OT hours to be on separate lines So my output would need to be something like below:

|Emp_ID|T_Date|Job_Code|Cost_Code|Reg_Hrs|OT_Hrs|
Data
|BR0000|..date|00000012|001234567|0000008|000000|
|BR0000|..date|00000012|001234567|0000000|000002|

I have tried some variations of UNION ALL statements and gotten close but not quite what I need since the second select does not create correct values or column layout.

SELECT `Emp_ID` AS `Emp_ID`,
    `T_Date` AS `T_Date`,
    SUBSTRING(CONCAT(`Job_Num`,`Job_let`),1,7) AS `Job_Code`,
    CONCAT(`Job_Code`, IFNULL(`Equip_Code`,'0000')) AS `Cost_Code,
    `Reg_Hrs` as `Reg_Hrs`,
    `OT_Hrs` as `OT_Hrs`
     FROM `timecard_payroll`
     WHERE `Reg_Hrs` <> 0
UNION ALL
SELECT `Emp_ID` AS `Emp_ID`,
       `T_Date` AS `T_Date`,
        SUBSTRING(CONCAT(`Job_Num`,`Job_let`),1,7) AS `Job_Code`,
        CONCAT(`Job_Code`, IFNULL(`Equip_Code`,'0000')) AS `Cost_Code,
        `Reg_Hrs` as `none`,  -- have tried different variations of these last 3 lines
        `OT_Hrs` as `OT_Hrs` FROM `timecard_payroll`
        WHERE `OT_Hrs` <> 0
ORDER BY `Emp_ID`, `T_Date`

I may have to write a PHP script to write to a temp table just for the export.

any help appreciated.

Formally:

SELECT {other columns}, Reg_Hrs * x.x Reg_Hrs, OT_Hrs * (1 - x.x) OT_Hrs
FROM source table
CROSS JOIN ( SELECT 0 x 
             UNION ALL
             SELECT 1 ) x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM