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
<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
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
LEFT JOIN
to make sure, you get complete list of companies even though there is no bill for any month.GROUP BY
to generate single record per company.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;