我使用Oracle SQL,试图写一个回答以下问题的语句:胜率高于分区平均数的NFL球队也具有比分区平均数更多的罚球数。
我有两个单独的语句,每个语句都可以单独返回(即:一个表,该表列出了获胜次数多于分区平均数的球队,另一个表中列出了获胜率高于平均数的球队)
但是,当我尝试将两个查询相交时,我遇到了错误。错误是“缺少选择关键字”。
WITH divisionPenaltyYards AS
(
SELECT division
,avg(penaltyyards) AS AVGPenalty
FROM nfl.teams
GROUP BY division
)
WITH divisionWins AS
(
SELECT division
,avg(wins) AS AVGWins
FROM nfl.teams
GROUP BY division
)
SELECT team
FROM nfl.teams
INNER JOIN divisionPenaltyYards
ON nfl.teams.division = divisionPenaltyYards.division
WHERE penaltyyards > AVGPenalty
INTERSECT
SELECT team
FROM nfl.teams
INNER JOIN divisionWins
ON nfl.teams.division = divisionWins.division
WHERE wins > AVGWins;
编辑:每个请求的更多信息
NFL.Teams由NFL中所有球队的统计数据组成。 球队,分区,胜利,罚球场……
数据集的示例包括
Packers, NFC NORTH, 6, 984
Steelers, AFC NORTH, 12, 817
等等。
期望的结果将是一张表格,列出所有获胜次数超过分区平均数的球队,同时还拥有比分区平均数更多的罚码。
答案 0 :(得分:2)
第二个CTE不应以holder.itemView.findViewById(R.id.my_view);
关键字开头。只是WITH
, divisionWins AS
这里也不需要使用两个CTE。
WITH divisionPenaltyYards AS
(
SELECT division
,avg(penaltyyards) AS AVGPenalty
FROM nfl.teams
GROUP BY division
)
, divisionWins AS
(
SELECT division
,avg(wins) AS AVGWins
FROM nfl.teams
GROUP BY division
)
SELECT team
FROM nfl.teams
INNER JOIN divisionPenaltyYards
ON nfl.teams.division = divisionPenaltyYards.division
WHERE penaltyyards > AVGPenalty
INTERSECT
SELECT team
FROM nfl.teams
INNER JOIN divisionWins
ON nfl.teams.division = divisionWins.division
WHERE wins > AVGWins;
此外,INTERSECT在这里工作,但UNION会更有意义。最终,两者都不需要:
WITH divisionCTE AS
(
SELECT division,
avg(penaltyyards) as avgpenalty,
avg(wins) as avgwins
FROM nfl.teams
GROUP BY division
)
SELECT team
FROM nfl.teams
INNER JOIN divisionCTE ON nfl.teams.division = divisionCTE.division
WHERE penaltyyards > AVGPenalty
INTERSECT
SELECT team
FROM nfl.teams
INNER JOIN divisionCTE ON nfl.teams.division = divisionCTE.division
WHERE wins > AVGWins;
最后,如果您想避免JOIN,则可以使用窗口函数:
WITH divisionCTE AS
(
SELECT division,
avg(penaltyyards) as avgpenalty,
avg(wins) as avgwins
FROM nfl.teams
GROUP BY division
)
SELECT team
FROM nfl.teams
INNER JOIN divisionCTE ON nfl.teams.division = divisionCTE.division
WHERE penaltyyards > AVGPenalty
AND wins > avgwins