我有两张桌子:
客户
id name
1 John
2 Kevin
customer_property
id customer_id code value
1 1 main_course
2 1 main_course
3 1 drink
4 1 drink
5 1 cash 100
我想要计算每个客户订购的课程和饮料。 我可以通过这个问题来计算饮料:
SELECT
c.name,
COUNT(DISTINCT cp.id) AS drinks_count
FROM customer AS c
JOIN customer_property AS cp ON c.id=cp.customer_id
WHERE cp.code="drink"
GROUP BY cp.id
工作正常。我的问题 - 可以在同一个查询中计算课程吗?
答案 0 :(得分:1)
您可以为此使用条件求和,并按cp.id
进行分组将为您提供该表中的许多行,您可以将其作为c.name
SELECT
c.name,
sum(cp.code="drink") AS drinks_count,
sum(cp.code="main_course") AS main_course_count,
FROM customer AS c
JOIN customer_property AS cp ON c.id=cp.customer_id
GROUP BY c.name
答案 1 :(得分:0)
你可以试试这个:
SELECT
c.name,
cp.code,
COUNT(DISTINCT cp.id) AS drink_or_course_count
FROM customer AS c
JOIN customer_property AS cp ON c.id=cp.customer_id
WHERE cp.code="drink" or cp.code="main_course"
GROUP BY cp.id,cp.code
按人员ID分类 AND 代码将按代码拆分计数。结果将类似于
Name Code drink_or_course_count
John drink 5
john main_course 3