合并使用相同表和相同列的两个查询

时间:2019-03-15 19:24:40

标签: mysql database oracle postgresql

因此,我试图为两个不同的功能使用相同的表和列创建查询。我可以分别创建每个查询,它可以平稳有效地运行。

第一个查询:

SELECT "y2018-cpsbsng"."fiscal_year" as "FY", 
"y2018-cpsbsn"."county", "y2018-cpstxsc"."child_population" as "Child Population", 
SUM("y2018-cpsbsng"."victims") AS "TOTAL ALLEGED"
FROM "y2018-cpstxsc" INNER JOIN "y2018-cpsbsng" USING ("county", "fiscal_year")
GROUP BY "y2018-cpsbsng"."fiscal_year", "y2018-cpsbsng"."county", "y2018-cpstxsc"."child_population"
ORDER BY "y2018-cpsbsng"."fiscal_year" ASC, "y2018-cpsbsng"."county" ASC

输出1:

FY county Child Population TOTAL ALLEGED 2008 Anderson 11237 808 2008 Andrews 3821 297

第二个查询:

SELECT "fiscal_year", "county", "victims" as "Confirmed Victims" 
FROM "y2018-cpsbsng" 
WHERE "victims" in 
(select "victims" FROM "y2018-cpsbsng" 
where "y2018-cpsbsng"."confirmed_victims" = 'Confirmed Victim')

输出2:

fiscal_year   county     Confirmed Victims
2008          Anderson   8
2008          Andrews    1

但是,一旦我尝试将两个查询合并为一个:

SELECT "fiscal_year","county", SUM("victims") AS "TOTAL ALLEGED",
victims
FROM "y2018-cpsbsng"
WHERE victims IN
(SELECT "victims"
FROM "y2018-cpsbsng" 
WHERE "y2018-cpsbsng"."confirmed_victims" = 'Confirmed Victim')
GROUP BY "fiscal_year", "county", victims
ORDER BY "fiscal_year" ASC,"county" ASC

发生这种情况(最终输出):

fiscal_year  county     TOTAL ALLEGED   victims
2008         Anderson   247             247
2008         Andrews    561             561

如果我摆脱了GROUP BY ....“受害者”(我认为是造成重复数字的原因),我将收到一条错误消息,指出{列“ y2018-cpsbsng.victims”必须出现在GROUP中BY子句或在聚合函数中使用 第1行:...“ ear”,“ county”,SUM(“ victims”)“ TOTAL ALLEGED”,“ victims”}以及我尝试修复的其他任何方式,该错误均表示{{子查询用作表达式}

谁能告诉我如何有效地结合这两个查询? 提前非常感谢您。

1 个答案:

答案 0 :(得分:0)

您可以JOIN将两个查询都作为表表达式。需要将ORDER BY提取到末尾。

例如:

select
  b."fiscal_year",
  a."county",
  a."TOTAL ALLEGED",
  b."Confirmed Victims" as "Vistims"
from ( -- first query
  SELECT "y2018-cpsbsng"."fiscal_year" as "FY", 
  "y2018-cpsbsn"."county", "y2018-cpstxsc"."child_population" as "Child Population", 
  SUM("y2018-cpsbsng"."victims") AS "TOTAL ALLEGED"
  FROM "y2018-cpstxsc" INNER JOIN "y2018-cpsbsng" USING ("county", "fiscal_year")
  GROUP BY "y2018-cpsbsng"."fiscal_year", "y2018-cpsbsng"."county", "y2018-cpstxsc"."child_population"
) a
join ( -- second query
  SELECT "fiscal_year", "county", "victims" as "Confirmed Victims" 
  FROM "y2018-cpsbsng" 
  WHERE "victims" in 
  (select "victims" FROM "y2018-cpsbsng" 
  where "y2018-cpsbsng"."confirmed_victims" = 'Confirmed Victim')
) b on a."FY" = b."fiscal_year"
ORDER BY a."FY" ASC, a."county" ASC -- now the ordering

如果您在一个查询中存在不存在于另一查询中的行,并且希望它们在结果查询中出现,则必须使用FULL OUTER JOIN而不是JOIN