简体   繁体   English

MySQL-如何将非唯一行转换为列并保持完整性?

[英]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. 我怀疑我必须在某个地方使用LIKE'Utilities%'。

tbl_charges 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. 我想将任何给定日期的两个房屋ID行组合在一起,并且只有该行的一行与“开销”在一列中,而“公用事业”在另一列中。 Essentially, I want just one row for any given House ID and Date. 本质上,对于任何给定的房屋ID和日期,我只想要一行。 The output for House ID 1 on 20170101 row should look like this: 20170101行上的房屋ID 1的输出应如下所示:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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