I have the following query, but I am stuck and am unsure where to go next with our museum's management application.
SELECT name,
account_number,
CASE
WHEN p.method = 'cash'
OR p.method = 'mo'
OR p.method = 'check'
THEN
MONTH(p.created_at)
ELSE
MONTH(p2.created_at)
END
FROM cemetery_charge_types
LEFT JOIN invoices i on cemetery_charge_types.id = i.charge_type_id
LEFT JOIN payment_details pd on i.id = pd.payable_id
LEFT JOIN payments p on pd.payment_id = p.id
LEFT JOIN payouts p2 on p.payout_id = p2.id
BETWEEN '2022-06-01 00:00:00' AND '2022-06-30 00:00:00'
WHERE cemetery_charge_types.category = 'Court'
GROUP BY account_number
ORDER BY account_number
If the p
(payments) method
is "cash, mo, or check" I want to group by month of p.created_at
and SUM by pd.amount
.
But if the p
(payments) method
is "card or terminal", I want to group by month of p2.created_at
.
I still want it grouped by the account_number
and to add the sums of both groups together.
So if cash, check or mo methods had a total of $100 for month 6 and a total of $0 for month 7. And if card and terminal methods had a total of $50 for month 6 and a total of $75 for month 7, I would want it to look like:
ACCT # MONTH 6 MONTH 7
Account 1 $150 $75
Is this at all possible, or does anyone have any suggestions of where I could look?
Thank you so much
Pattern:
SELECT {common columns},
CASE WHEN {condition 1} THEN {expression 1}
WHEN {condition 2} THEN {expression 2}
END AS grouping_expression,
SUM( CASE WHEN {condition 1} THEN {value 1}
WHEN {condition 2} THEN {value 2}
END ) AS result_expression
FROM {tableset}
GROUP BY {common columns},
grouping_expression
Table structure with sample data will help to understand question. That CASE statement must go as part of Group clause.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.