PostgreSQL SQL根据table2中的条件从table1中选择项目

时间:2018-12-19 16:37:52

标签: sql postgresql conditional

我正在尝试从具有子table2的table1中选择项目,其中涉及第三个table3。

Select j.ccmasterid, 
(Select sum(i.ccmatpullqty) From table2 i 
 Where i.ccmasterid = j.ccmasterid)  pulled
 from table1 j
INNER JOIN table3 s on j.ccstatus = s.sysstatusid and s.ccopenjob=false
where j.ccmasterid LIKE 'W%' and pulled = 0  

这会产生一个错误:

  

错误:“拉”列不存在   第6行:其中j.ccmasterid喜欢'W%'并拉取= 0

如果我从查询中取出“ and pull = 0 ”,它的工作原理就如同期望从table1中产生一个记录列表,其中table2中的值之和被拉出一样。

ccmasterid    pulled
W106063            0
W100553            9
W100685            1

我不知道如何基于拉为0进行选择。

2 个答案:

答案 0 :(得分:1)

将此查询更改为子查询,并将WHERE条件移动到外部查询:

SELECT * FROM (
   Select j.ccmasterid, 
   (Select sum(i.ccmatpullqty) From table2 i 
    Where i.ccmasterid = j.ccmasterid)  pulled
    from table1 j
   INNER JOIN table3 s on j.ccstatus = s.sysstatusid and s.ccopenjob=false
   where j.ccmasterid LIKE 'W%'
) x
WHERE  pulled = 0  

答案 1 :(得分:0)

如果关联到带有GROUP BY子句的汇总查询,则避免在外部查询中的行中运行而不是在一次中运行的相关子查询:

SELECT j.ccmasterid
FROM table1 j
INNER JOIN table3 s 
    ON j.ccstatus = s.sysstatusid AND s.ccopenjob = false
INNER JOIN
   (SELECT i.ccmasterid, SUM(i.ccmatpullqty) AS pulled
    FROM table2 i 
    GROUP BY i.ccmasterid
   ) AS agg
    ON agg.ccmasterid = j.ccmasterid
WHERE j.ccmasterid LIKE 'W%' AND agg.pulled = 0  

甚至使用CTE

WITH agg AS
    (SELECT i.ccmasterid, SUM(i.ccmatpullqty) AS pulled
     FROM table2 i 
     GROUP BY i.ccmasterid)

SELECT j.ccmasterid
FROM table1 j
INNER JOIN table3 s 
    ON j.ccstatus = s.sysstatusid AND s.ccopenjob = false
INNER JOIN agg
    ON agg.ccmasterid = j.ccmasterid
WHERE j.ccmasterid LIKE 'W%' AND agg.pulled = 0