简体   繁体   中英

MySQL - How to convert non-unique rows into columns and maintain integrity?

I want to convert this table into another table with the row of Bill Type being two distinct columns, one for Utilities and one for Overhead. I suspect I'd have to use a LIKE 'Utilities%' in there somewhere.

tbl_charges

House ID  Account  AC Type    Date          Bill Type       Amount
---------------------------------------------------------------------
1        1        A        20170101      Overhead           40.00
1        1        A        20170101      Utilities @ Elec   15.50
---------------------------------------------------------------------
2        1        B        20170101      Overhead           35.00
2        1        B        20170101      Utilities @ Elec   25.50
---------------------------------------------------------------------
3        2        B        20170101      Overhead           42.00
3        2        B        20170101      Utilities @ Water  18.25
---------------------------------------------------------------------
1        1        A        20170301      Overhead           39.00
1        1        A        20170301      Utilities @ Elec   19.50
---------------------------------------------------------------------
4        4        A        20170201      Overhead           55.00
4        4        A        20170201      Utilities @ Water  17.25

I want to combine the two House ID rows for any given Date and just have one row for that date with the Overhead in one column and the Utilities in another column. Essentially, I want just one row for any given House ID and Date. The output for House ID 1 on 20170101 row should look like this:

House ID  Account  AC Type    Date     Overhead  Utilities  Total Amount
1         1        A          20170101 40.00     15.50      55.50
 SELECT HouseId, Account, `AC Type`, Date, 
        MAX( CASE WHEN BillType = 'Overhead' THEN Amount END) as Overhead,
        MIN( CASE WHEN BillType LIKE  'Utilities%' THEN Amount END) as Utilities,
        SUM(Amount) as `Total Amount`
FROM YourTable
GROUP BY HouseId, Account, `AC Type`, Date 

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