简体   繁体   English

SQL中匹配项的总和

[英]Sum matching entries in SQL

In this database I need to find the total amount that each customer paid for books in a category, and then sort them by their customer ID. 在此数据库中,我需要找到每个客户为某个类别的图书支付的总金额,然后按其客户ID对其进行排序。 The code appears to run correctly but I end up with approximately 20 extra rows than I should, although the sum appears to be correct in the right rows. 该代码似乎可以正确运行,但是尽管总和在正确的行中看起来是正确的,但最终却比我多了大约20行。

The customer ID is part of customer , but is not supposed to appear in the select clause, when I try and ORDER BY it, I get strange errors. 客户ID是一部分customer ,但不应该出现在select条款,当我尝试和ORDER BY的话,我一些奇怪的错误。 The DB engine is DB2. DB引擎是DB2。

SELECT distinct customer.name, book.cat, sum(offer.price) AS COST
FROM offer

INNER JOIN purchase ON purchase.title=offer.title
INNER JOIN customer ON customer.cid=purchase.cid
INNER JOIN member ON member.cid=customer.cid
INNER JOIN book ON book.title=offer.title

WHERE
member.club=purchase.club
AND member.cid=purchase.cid AND purchase.club=offer.club
GROUP BY customer.name, book.cat;

You should fix your join conditions to include the ones in the where clause (between table relationships usually fit better into an on clause). 您应该修复join条件,以将其包括在where子句中(表关系之间通常更适合on子句)。

SELECT DISTINCT is almost never appropriate with a GROUP BY . SELECT DISTINCT几乎不适合使用GROUP BY

But those are not your question. 但这不是你的问题。 You can use an aggregation function: 您可以使用聚合函数:

GROUP BY customer.name, book.cat
ORDER BY MIN(customer.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM