我使用了一系列基本的非嵌套SQL View查询来慢慢过滤来自多个表的数据,以获得我所追求的结果。第一个查询使用基本关系作为输入,后续查询使用基本关系和/或前一个查询的结果。最终查询显示了我之后的结果。
首先查询:
CREATE VIEW ActiveRobbers
AS
SELECT a.RobberID, Nickname, NoYears, BankName, Share
FROM info.Robber a, info.Accomplices b
WHERE a.RobberID = b.RobberID;
第二次查询:
CREATE VIEW ActiveRobbers2
AS
SELECT Nickname, NoYears, COUNT(RobberID) AS NoRobberies, SUM(Share) AS TotalEarnings
FROM ActiveRobbers
GROUP BY Nickname, NoYears;
最终查询:
CREATE VIEW ActiveRobbers3
AS
SELECT Nickname
FROM ActiveRobbers2
WHERE NoYears = 0
AND NoRobberies > (SELECT AVG(NoRobberies) FROM ActiveRobbers2);
如何使用select语句将其转换为单个嵌套查询?你可以使用某种规则吗?我是否因为筑巢而倒退?
答案 0 :(得分:0)
如果您正在学习SQL,请学会使用正确且明确的join
语法。所以你的第一个查询是:
SELECT r.RobberID, a.Nickname, a.NoYears, a.BankName, a.Share
FROM info.Robber r JOIN
info.Accomplices a
on r.RobberID = a.RobberID;
第二个:
SELECT a.Nickname, a.NoYears, COUNT(*) as NumRobberies, SUM(Share) as TotalEarnings
FROM info.Robber r JOIN
info.Accomplices a
on r.RobberID = a.RobberID
GROUP BY a.Nickname, a.NoYears
第三个:
WITH ActiveRobbers2 as (
SELECT a.Nickname, a.NoYears, COUNT(*) as NumRobberies, SUM(Share) as TotalEarnings
FROM info.Robber r JOIN
info.Accomplices a
on r.RobberID = a.RobberID
GROUP BY a.Nickname, a.NoYears
)
SELECT a.*
FROM ActiveRobbers2 a
WHERE NoYears = 0 AND
NumRobberies > (SELECT AVG(NumRobberies) FROM ActiveRobbers2);
实际上,我会使用窗口函数编写第三个版本,但是我会把你的逻辑留在问题中。