如何将一组基本(非嵌套)视图转换为单个嵌套查询?

时间:2015-08-23 09:17:58

标签: sql postgresql psql

我使用了一系列基本的非嵌套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;

Result from first query

第二次查询:

CREATE VIEW ActiveRobbers2
AS
SELECT Nickname, NoYears, COUNT(RobberID) AS NoRobberies, SUM(Share) AS    TotalEarnings
FROM ActiveRobbers
GROUP BY Nickname, NoYears;

Result from second query

最终查询:

CREATE VIEW ActiveRobbers3
AS  
SELECT Nickname
FROM ActiveRobbers2
WHERE NoYears = 0
AND NoRobberies > (SELECT AVG(NoRobberies) FROM ActiveRobbers2);

Result from third query

如何使用select语句将其转换为单个嵌套查询?你可以使用某种规则吗?我是否因为筑巢而倒退?

1 个答案:

答案 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);

实际上,我会使用窗口函数编写第三个版本,但是我会把你的逻辑留在问题中。