Postgres where子句来自子查询的两列

时间:2017-09-25 13:58:46

标签: sql postgresql select subquery where-clause

  • 数据库:Postgres
  • 表名:records
  • 有4列Year | Dept | Expense | Month

因此,每年/每个部门最多可以有一个记录。

我有一个子查询,它根据约束返回下面的数据。

Year | Dept
2001 | HR
2001 | ACC
2001 | TECH
2002 | TECH
2003 | HOUSE-KEEPING
2003 | TECH

现在,我需要在同一个表上运行另一个查询,以获得每个值对的总费用。

使用子查询的输出,我的主查询将类似于

select Dept, sum(Expense) 
from records 
where (Year, Dept) in (...)
... I want to iterate over value pairs from the subquery

(SUBQUERY which returns
Year | Dept
2001 | HR
2001 | ACC
2002 | TECH
2003 | HOUSE-KEEPING
)

当我运行此select语句时,返回的输出仅包含三年内TECH的数据。

请帮助理解我如何在子查询的所有行上运行主选择

3 个答案:

答案 0 :(得分:8)

将子查询重构为连接。

说你有

SELECT a, b FROM t1 WHERE (x,y) IN (SELECT x1, y1 FROM t2 WHERE ...)

不会起作用。你重写为

SELECT a, b
FROM t1
INNER JOIN (
   -- subquery here:
   SELECT x1, y1
   FROM t2
   WHERE ...
) AS some_alias
WHERE t1.x = some_alias.x1
  AND t1.y = some_alias.y1;

注意,in PostgreSQL you shouldn't use a CTE (WITH query) for this

您可以缩写

WHERE t1.x = some_alias.x1
  AND t1.y = some_alias.y1;

WHERE (x, y) = (x1, y1)

虽然。

答案 1 :(得分:1)

如果您还没有数百万行,您可以通过将值连接到一个值来保持查询的语义:

select Dept, sum(Expense)
from records
where Year || Dept in (select Year || Dept from ...)

它易于阅读,理解和维护,除非你有数万年的时间和部门,否则它会表现得很好,这似乎不太可能。

答案 2 :(得分:-1)

解决方案pact-web

SELECT dept, SUM(expense) FROM records 
WHERE ROW(year, dept) IN (SELECT x, y FROM otherTable)
GROUP BY dept;

found here函数发挥了神奇作用。