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

前端 未结 3 1976
时光取名叫无心
时光取名叫无心 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

提交回复
热议问题