我正在做一个关于SQL查询的练习,当谈到SUM时我想出了一个错误。我知道这是做什么,但我不知何故得到错误......
select
client.LName, client.FName,
COUNT(b.Total)
from
ClientBank client
INNER JOIN
Bank b ON (client.ClientID = b.ClientID)
where
client.LName = 'name' AND client.FName = 'a';
但后来我收到了这个错误...
列'ClientBank.LName'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
我试过做一个Group BY,真的不知道如何使用它..任何帮助都会很棒!
答案 0 :(得分:1)
您尚未给出ClientBank
和Bank
表的结构。我正在考虑你插入这样的记录:
INSERT INTO `ClientBank`
(`ClientID`, `FName`, `Lname`)
VALUES
(1, 'Abraham', 'Backman'),
(2, 'Carl', 'Dacosta'),
(3, 'Erwin', 'Fabio'),
(4, 'Gabriel', 'Haddon');
INSERT INTO `Bank`
(`DepositID`, `ClientID`, `Deposit`)
VALUES
(1, 1, 100),
(2, 2, 200),
(3, 3, 300),
(4, 4, 400),
(5, 2, 500),
(6, 3, 600);
您可以通过以下方式获得每个客户的存款总额:
SELECT
client.LName, client.FName, SUM(b.Deposit) as Total
FROM
ClientBank client
INNER JOIN
Bank b ON (client.ClientID = b.ClientID)
GROUP By
client.LName, client.FName;
如果您只想要特定客户端(使用他们的名称进行过滤而不是客户端ID):
SELECT
client.LName, client.FName, SUM(b.Deposit) as Total
FROM
ClientBank client
INNER JOIN
Bank b ON (client.ClientID = b.ClientID)
WHERE
client.LName = 'Fabio' AND client.FName = 'Erwin'
GROUP By
client.LName, client.FName;