我有2个表,一个包含peopleID和名字的人员表,以及一个他们所做的承诺表,其中有一个pledgeID(1到6),一个personID来说明它来自谁,以及一个金额字段。
我们需要有一个查询,提供一个明确的人员列表,他们总共承诺了多少,以及他们认为正确的承诺数量(pledgeIDs 1,3和5将被认为是正确的)
所以我们需要知道,例如约翰史密斯总共认捐了500英镑,并且他认可了2个承诺(因为他已经承诺了1,3和6),而萨莉詹姆斯承诺2000英镑并承诺在ids 1,3和5上,因此匹配3
我希望这很清楚。我真的很感激这个帮助。
非常感谢
戴夫
答案 0 :(得分:2)
听起来像这样的东西会起作用:
SELECT PersonID,
SUM(Amount) AS TotalPledged,
SUM(CASE WHEN PledgeID IN (1,3,5) THEN 1 ELSE 0 END) AS CorrectPledges
FROM PersonPledges
GROUP BY PersonID
答案 1 :(得分:0)
如果您使用主表作为承诺,您可以像这样一次性获取所有信息:
SELECT People.PersonName, pledgetotals.PledgeTotal, pledgecounts.PledgesCorrect FROM People
LEFT OUTER JOIN (SELECT PeoplePledges.peopleID, SUM(PeoplePledges.pledgeAmount) AS PledgeTotal FROM PeoplePledges GROUP BY PeoplePledges.peopleID) pledgetotals ON People.peopleID = pledgetotals.peopleID
LEFT OUTER JOIN (SELECT PeoplePledges.peopleID, COUNT(DISTINCT PeoplePledges.pledgeID) AS PledgesCorrect FROM PeoplePledges JOIN Pledge ON PeoplePledges.pledgeID = Pledge.pledgeID WHERE Pledge.correct = 1 GROUP BY PeoplePledges.peopleID) pledgecounts ON People.peopleID = pledgecounts.peopleID
希望它不太清楚;每个子查询都需要进行汇总(汇总承诺金额和分别计算正确的承诺);如果您使用左外连接以这种方式排列查询,您可以列出所有相关人员,无论他们是否真的有任何承诺。
编辑:这就是我所承诺的'主表'的意思:
CREATE TABLE Pledge (INT pledgeID INT PRIMARY KEY, correct BOOLEAN NOT NULL);
INSERT INTO Pledge (pledgeID, correct) VALUES (1, 1);
INSERT INTO Pledge (pledgeID, correct) VALUES (2, 0);
INSERT INTO Pledge (pledgeID, correct) VALUES (3, 1);
INSERT INTO Pledge (pledgeID, correct) VALUES (4, 0);
INSERT INTO Pledge (pledgeID, correct) VALUES (5, 1);
INSERT INTO Pledge (pledgeID, correct) VALUES (6, 0);
编辑:如果您无法添加主承诺表,那么您必须在代码中使用“魔术数字”,但结构非常相似:
SELECT People.PersonName, pledgetotals.PledgeTotal, pledgecounts.PledgesCorrect FROM People
JOIN (SELECT PeoplePledges.peopleID, SUM(PeoplePledges.pledgeAmount) AS PledgeTotal FROM PeoplePledges GROUP BY PeoplePledges.peopleID) pledgetotals ON People.peopleID = pledgetotals.peopleID
JOIN (SELECT PeoplePledges.peopleID, COUNT(DISTINCT PeoplePledges.pledgeID) AS PledgesCorrect FROM PeoplePledges WHERE PeoplePledges.pledgeID IN (1,3,5) GROUP BY PeoplePledges.peopleID) pledgecounts ON People.peopleID = pledgecounts.peopleID
答案 2 :(得分:-1)
最简单的方法是:
1-从你人民的桌子上获取所有人,例如:
SELECT peopleId, name FROM people
2-遍历每一行并获得每个人的承诺。在PHP中你会做这样的事情:
foreach ($people as $k=>$person)
{
$sql = "SELECT SUM(amount) as total FROM pledges
WHERE peopleId = '$person[peopleId]'";
$result = mysql_query($sql);
if (mysql_num_rows($result) <= 0)
$total = '0';
else
{
$row = mysql_fetch_assoc($result);
$total = $row['total'];
}
$people[$k]['total'] = $total;
}