I would like to add some SUMs from subqueries in the SELECT into another new field. Here is the query that I am currently using:
SELECT DAYNAME(date) AS day, DATE_FORMAT(date, "%d-%m-%Y") AS date,
(SELECT SUM(qty) AS product1_shift1
FROM bill_details
JOIN bills ON bills.bill_id=bill_details.bill_id
WHERE bills.shift_id='48c73e3d-57de-4fea-aae4-7222d7e6afed'
AND bills.date=bills_master.date) AS product1_shift1,
(SELECT SUM(qty) AS product1_shift2
FROM bill_details
JOIN bills ON bills.bill_id=bill_details.bill_id
WHERE bills.shift_id='463ec995-cfad-46ff-8e65-3115e6e651c5'
AND bills.date=bills_master.date) AS product1_shift2,
(SELECT SUM(qty) AS product1_shift3
FROM bill_details
JOIN bills ON bills.bill_id=bill_details.bill_id
WHERE bills.shift_id='0a792c5f-84a6-4534-818c-427cfe8cd3ca'
AND bills.date=bills_master.date) AS product1_shift3
FROM bills bills_master
GROUP BY bills_master.date
Notice that the product1_shift1 field is a subquery result. I would like to do the product1_shift1+product1_shift2+prdduct1_shift3. I keep getting the
Unknown column ‘product1_shift1’ in ‘field list’
error when I tried to add another SELECT field like
product1_shift1+product1_shift2+product1_shift3
.
How can I solve this? Thank you.
2
Answers
You don’t need the subqueries.
Use a
LEFT
join ofbills
tobill_details
and conditional aggregation:You can put your sql query in a CTE then calculate your total as follows :