我现在才开始学习SQL,并试图找出这种情况:
我们有3张桌子:
SELECT CONCAT(IFNULL(Name,''),' ', IFNULL(Surname,'')) as FullName,
COUNT(purchaseId) as "Quantity of purchases"
FROM Purchases as P
INNER JOIN Clients as C
on P.ClientID = C.ClientID
GROUP BY C.ClientID,Name, Surname
HAVING COUNT(PurchaseId) > 1;
显示客户购买量(每个客户的总金额)的最佳SQL查询是什么?
它必须仅显示购买超过1次的客户。
结果应包含以下字段:全名,购买数量,总金额。
我有这个查询,但是它只连接两个表。如何同时加入第三张表(Products.Price)并计算每个客户的总金额?
fun <T> Observable<T>.subscribeIf(predicate: () -> Boolean) {
if (predicate()) {
subscribe()
}
}
答案 0 :(得分:0)
您可以在下面尝试-
SELECT CONCAT(IFNULL(Name,''),' ', IFNULL(Surname,'')) as FullName,
COUNT(purchaseId) as "Quantity of purchases",sum(price) as totalamount
FROM Purchases as P
INNER JOIN Clients as C
on P.ClientID = C.ClientID
inner join Products p1 on p.productid=p1.productid
GROUP BY C.ClientID,Name, Surname
HAVING COUNT(PurchaseId) > 1
答案 1 :(得分:0)
您再次使用INNER JOIN
,例如:
SELECT CONCAT(IFNULL(Name,''),' ', IFNULL(Surname,'')) as FullName,
COUNT(purchaseId) as "Quantity of purchases"
FROM Purchases as P
INNER JOIN Clients as C
on P.ClientID = C.ClientID
INNER JOIN Products as PR
on PR.ProductID = P.ProductID
GROUP BY C.ClientID,Name, Surname
HAVING COUNT(PurchaseId) > 1;
答案 2 :(得分:0)
我建议您使用CONCAT_WS()
来组合名字。这比您的解决方案更优雅地处理NULL
值。
SELECT CONCAT_WS(c.Name, c.Surname) as FullName,
COUNT(*) as num_purchases,
SUM(pr.price) as total_price
FROM Clients c INNER JOIN
Purchases p
ON P.ClientID = C.ClientID INNER JOIN
Products pr
ON pr.ProductID = p.ProductID
GROUP BY CONCAT_WS(c.Name, c.Surname)
HAVING COUNT(DISTINCT p.PurchaseId) > 1;
请注意COUNT(DISTINCT)
子句中的HAVING
。这样可以确保客户至少有两个购买。如果您只希望客户购买至少两个产品或购买的商品,则可以使用COUNT(*)
-但您的问题是关于购买的。