mysql 分组并加入
mysql groupby and join
我想按“食物”和“饮料”等菜单类型从 bar_purchase_request table 组中获取总计。我试过以下查询:
SELECT DISTINCT(b.name),
0 as food_total,
0 as drink_total,
sum(ph.total) as total,
sum(ph.gratuity) as gratuity
from branches b
LEFT JOIN drink_requests dr ON b.id = dr.branch_id
JOIN drink_food df ON df.id = dr.drink_id
JOIN bar_purchase_history ph ON ph.request_id = dr.id
GROUP BY dr.branch_id;
你可以检查我的 table 结构如下:
请求table结构:
菜单项table结构:
我想要这样的结果:
任何人都可以提供帮助。
我创建了查询并为我工作:
SELECT b.name as branch_name,SUM(CASE WHEN df.type = 'drink' THEN bph.price ELSE 0 END) as totalDrink,SUM(CASE WHEN df.type = 'food' THEN bph.total ELSE 0 END) as totalFood,SUM(bph.gratuity) as gratuity, sum(bph.total) as total FROM bar_purchase_history bph JOIN drink_food df ON bph.item_id = df.id JOIN drink_requests dr ON bph.request_id = dr.id JOIN branches b ON dr.branch_id = b.id where dr.branch_id = 1 GROUP BY dr.branch_id;
我想按“食物”和“饮料”等菜单类型从 bar_purchase_request table 组中获取总计。我试过以下查询:
SELECT DISTINCT(b.name),
0 as food_total,
0 as drink_total,
sum(ph.total) as total,
sum(ph.gratuity) as gratuity
from branches b
LEFT JOIN drink_requests dr ON b.id = dr.branch_id
JOIN drink_food df ON df.id = dr.drink_id
JOIN bar_purchase_history ph ON ph.request_id = dr.id
GROUP BY dr.branch_id;
你可以检查我的 table 结构如下:
请求table结构:
菜单项table结构:
我想要这样的结果:
任何人都可以提供帮助。
我创建了查询并为我工作:
SELECT b.name as branch_name,SUM(CASE WHEN df.type = 'drink' THEN bph.price ELSE 0 END) as totalDrink,SUM(CASE WHEN df.type = 'food' THEN bph.total ELSE 0 END) as totalFood,SUM(bph.gratuity) as gratuity, sum(bph.total) as total FROM bar_purchase_history bph JOIN drink_food df ON bph.item_id = df.id JOIN drink_requests dr ON bph.request_id = dr.id JOIN branches b ON dr.branch_id = b.id where dr.branch_id = 1 GROUP BY dr.branch_id;