Lets say I have two tables, cart and cart_items. This is all via MySQL…
cart
[table=“width: 300, class: grid, align: left”]
[tr]
[td]id[/td]
[td]bunch of other fields[/td]
[/tr]
[tr]
[td]1[/td]
[td]…[/td]
[/tr]
[tr]
[td]2[/td]
[td]…[/td]
[/tr]
[/table]
cart_items
[table=“width: 300, class: grid, align: left”]
[tr]
[td]id[/td]
[td]cart_id[/td]
[td]category[/td]
[td]item[/td]
[td]qty[/td]
[td]price[/td]
[/tr]
[tr]
[td]1[/td]
[td]1[/td]
[td]A[/td]
[td]widget1[/td]
[td]5[/td]
[td]10.00[/td]
[/tr]
[tr]
[td]2[/td]
[td]1[/td]
[td]A[/td]
[td]widget2[/td]
[td]1[/td]
[td]25.00[/td]
[/tr]
[tr]
[td]3[/td]
[td]1[/td]
[td]B[/td]
[td]widget3[/td]
[td]2[/td]
[td]2.50[/td]
[/tr]
[tr]
[td]4[/td]
[td]1[/td]
[td]C[/td]
[td]widget4[/td]
[td]1[/td]
[td]9.00[/td]
[/tr]
[/table]
Every cart has a list of items with an assigned category (A, B, C, etc.). What I’d like to do is get sums of all category A items, sums of all other categories (B, C, etc.) and then all individual items:
[table=“class: grid, align: left”]
[tr]
[td]cart_id[/td]
[td]A_totals[/td]
[td]non_A_totals[/td]
[td]cart_totals[/td]
[td]item[/td]
[td]qty[/td]
[td]price[/td]
[td]ext price[/td]
[td]category[/td]
[/tr]
[tr]
[td]1[/td]
[td]75.00[/td]
[td]14.00[/td]
[td]89.00[/td]
[td]widget1[/td]
[td]5[/td]
[td]10.00[/td]
[td]50.00[/td]
[td]A[/td]
[/tr]
[tr]
[td]1[/td]
[td]75.00[/td]
[td]14.00[/td]
[td]89.00[/td]
[td]widget2[/td]
[td]1[/td]
[td]25.00[/td]
[td]50.00[/td]
[td]A[/td]
[/tr]
[tr]
[td]1[/td]
[td]75.00[/td]
[td]14.00[/td]
[td]89.00[/td]
[td]widget3[/td]
[td]2[/td]
[td]2.50[/td]
[td]5.00[/td]
[td]B[/td]
[/tr]
[tr]
[td]1[/td]
[td]75.00[/td]
[td]14.00[/td]
[td]89.00[/td]
[td]widget4[/td]
[td]1[/td]
[td]9.00[/td]
[td]9.00[/td]
[td]C[/td]
[/tr]
[/table]
What I’m unsure of is how to basically do a group by to select the totals for a given cart, but also include the individual lines that are summed up for that group. Basically I need the group by details to show up in every single line? Is this possible?
I can do this using two queries - one to select the totals, and one to select the individual items but I’m not sure if and how to do this in one.
Here’s how I’m currently selecting the totals:
SELECT c.id
, SUM(IF(ci.category = 'A', ci.qty * ci.price, 0) AS A_totals
, SUM(IF(ci.category = 'A', 0, ci.qty * ci.price) AS non_A_totals
, SUM(ci.qty * ci.price) AS cart_totals
FROM cart c
LEFT JOIN cart_items ci ON c.id = ci.cart_id
GROUP BY c.id
Any help?