Fetch last 3 month data as separate columns not rows for each user

前端 未结 3 1977
时光取名叫无心
时光取名叫无心 2021-01-27 00:48

i have a mysql table \"bf_monthly_bill\" in which data against each users from another table \"bf_users\" is stored month wise.

Structure of my bf_users table is

<
相关标签:
3条回答
  • 2021-01-27 01:07

    Try this::

    SELECT bu.name, 
        max(case when (bb.bill_month='Jan2k19') then bb.package_price else NULL end) as 'first_month_bill',
        max(case when (bb.bill_month='Feb2k19') then bb.package_price else NULL end) as 'second_month_bill',
        max(case when (bb.bill_month='Mar2k19') then bb.package_price else NULL end) as 'third_month_bill'
        FROM bf_users bu
        INNER JOIN bf_monthly_bill bb
        ON bu.id = bb.bf_users_id GROUP BY bu.name;
    

    Output::

    name    first_month_bill    second_month_bill   third_month_bill
    ABC       500                   200                  500
    DEF       300                  (null)                300
    GHI       900                   542                  900
    JKL      (null)                (null)                200
    

    Here is SQLFiddle demo

    0 讨论(0)
  • 2021-01-27 01:08

    You can try using conditional aggregation

    select display_name,
           sum(case when bill_month='Jan2k19' then package_price end) as first_bill,
           sum(case when bill_month='Feb2k19' then package_price end) as second_bill,
           sum(case when bill_month='Mar2k19' then package_price end) as third_bill
    from
    (
       SELECT u.display_name,b.package_price,b.bill_month
       from bf_users u inner join bf_monthly_bill b on u.id=b.company_id
    )A group by display_name
    
    0 讨论(0)
  • 2021-01-27 01:12
    1. Use LEFT JOIN to make sure, you get complete list of companies even though there is no bill for any month.
    2. You have to create n columns manually or using a script.
    3. You can just do simple join, no subquery is required.
    4. Use GROUP BY to generate single record per company.
    5. Use CASE WHEN or IF ELSE to create n columns and pick data from relevent row only. It can be first or any row, so use aggregate function to pick data even it is at any row for a group by making other row values as NULL as aggregate function exclude null values.
    SELECT 
        u.display_name,
        SUM(IF( bill_month='Jan2k19', package_price, NULL)) as first_bill,
        SUM(IF( bill_month='Feb2k19', package_price, NULL)) as second_bill,
        SUM(IF( bill_month='Mar2k19', package_price, NULL)) as third_bill
    FROM bf_users u 
    LEFT JOIN bf_monthly_bill b on u.id=b.company_id
    GROUP BY u.display_name;
    
    
    0 讨论(0)
提交回复
热议问题