有一个客户列表,其中包含客户列表。
我有2个表,customers
和invoices
。
Customer_id
对我的客户来说可能是相同的,例如
客户A
Customer #1
客户B
Customer #1
因此,对于不同的客户,发票表的customer_id可以为1。
以下查询有效,但看起来有点凌乱。有任何清理它的想法吗?
SELECT name,
sum(sub_total) total
FROM customers, invoices
WHERE customer_id = 1438 and
invoices.customer_id = 1438 and
customers.customer_id = invoices.customer_id
GROUP BY name
Order By total DESC;
答案 0 :(得分:4)
如果A = B
和A = 1438
然后B = 1438
您不需要检查它...
(相信我这个,我在高中学习数字 60 + )
SELECT name, sum(sub_total) total
FROM customers, invoices
WHERE invoices.customer_id = 1438
AND customers.customer_id = invoices.customer_id
GROUP BY name
ORDER BY total DESC;
或者明确说明你想要哪种类型的JOIN:
SELECT name, sum(sub_total) total
FROM customers INNER JOIN invoices
ON customers.customer_id = invoices.customer_id
WHERE invoices.customer_id = 1438
GROUP BY name
ORDER BY total DESC;
答案 1 :(得分:1)
你不需要额外的支票......
SELECT name, sum(sub_total) total
FROM customers, invoices
WHERE
customer_id = 1438 and
customers.customer_id = invoices.customer_id
GROUP BY name order by total DESC;
答案 2 :(得分:1)
我强烈不会在名字上做一个小组...假设你有两个名为“Bill Smith”的客户,但一个是客户ID 10,另一个是客户ID 785 ......你只是将它们组合成一个单身人士。你应该按ID分组,而不是名字......
现在,就是说,无论如何,您只查询一个客户ID,并且只会返回一条记录。如果您真正想要完成的是获取所有客户及其各自的发票,请删除单个客户的where子句。您可以按ID保留组,但显示实际客户的名称。如果您有多个客户具有相同的总数,则可以按名称进行子排序,但分组仅基于客户的ID进行分组。
SELECT
c.name,
sum(i.sub_total) total
FROM
customers
JOIN invoices
on c.Customer_ID = i.Customer_ID
GROUP BY
c.customer_ID
Order By
total DESC,
c.Name