我的Oracle数据库中有三个表:
人民:
IdPerson PK
Name
Surname
收益:
IdEarning
IdPerson
EarningValue
奖
IdAward PK
IdPerson FK
AwardDescription
我想创建一个返回3列的查询:
重要的是,如果有人没有奖励或赚钱,我还需要显示:0值。人有可能获得奖励,但没有任何收入。
是否可以进行此类查询?
答案 0 :(得分:0)
是的,有可能,你只需要加入表格
SELECT Peoples.Surname, SUM(Earnings.EarningValue) as Earnings, COUNT(Awards. IdPerson) as Awards
FROM Peoples
INNER JOIN Earnings
ON Peoples.IdPerson = Earnings.IdPerson
INNER JOIN Awards
ON Peoples.IdPerson = Awards.IdPerson
GROUP BY Peoples.IdPerson;
答案 1 :(得分:0)
是的,当然有可能。 你只需要使用多个连接查询来连接表,然后应用sum()函数来获得收益和Count()来计算no。奖项。 请尝试以下查询:
SELECT P.Surname,
Sum(E.EarningValue)AS Total_Earnings,
Count(A.IdAward) AS total_awards
FROM Peoples P
LEFT JOIN Earnings E
ON P.IdPerson = E.IdPerson
LEFT JOIN Awards A
ON A.IdPerson = P.IdPerson
GROUP BY P.IdPerson;
答案 2 :(得分:0)
SELECT p.IdPerson,
p.Surname,
NVL(SUM(e.EarningValue), 0) as SumEarnings,
COUNT(a.IdAward) as CntAwards
FROM Peoples p
LEFT JOIN Earnings e ON p.IdPerson = e.IdPerson
LEFT JOIN Awards a ON p.IdPerson = a.IdPerson
GROUP BY p.IdPerson,
p.Surname;
返回什么:
SELECT p.Surname,
(SELECT NVL(SUM(e.EarningValue), 0)
FROM Earnings e WHERE e.IdPerson = p.IdPerson) as SumEarnings,
(SELECT COUNT(aIdAward)
FROM Awards a WHERE a.IdPerson = p.IdPerson) as CntAwards
FROM Peoples p