在两个结果集上应用连接 - Postgres

时间:2017-05-16 13:01:16

标签: postgresql

我有查询给了我文件

select documentid from tbldocumentbyclient
where tbldocumentbyclient.isactive = true
and applicationid = '000116'

结果:

另一个给我以下结果的查询

SELECT  documentcategory,documentcategoryid, string_agg(documentid::text, ',')   as documentid
                        FROM  tbldocumentmaster 
                        where accounttype = 1 and usertype= 'INDIVIDUAL'
                        group by documentcategory,documentcategoryid
                        order by documentcategoryid;

结果: [![在此处输入图像说明] [2]] [2]

现在,有人可以建议我如何获取与任何文档相关的CategoryName

对于以上情况,我的结果应该是以下。

  1. DP Proof - 134在第一个结果中不可用
  2. 地址证明永久 - 第4行..而不是文件结果中可用的单个ID
  3. 这是与任何文档ID无关的文档类别

3 个答案:

答案 0 :(得分:2)

我认为两个表之间的简单连接应该可以解决问题。这里的逻辑是,如果来自tbldocumentmaster的文档类别确实没有与tbldocumentbyclient表中的任何内容匹配的文档ID,则联接应该将其过滤掉,留下那些匹配的类别。

SELECT t1.documentcategory
FROM tbldocumentmaster t1
LEFT JOIN tbldocumentbyclient t2
    ON t1.documentid = t2.documentid
WHERE t2.isactive = true          AND
      t2.applicationid = '000116' AND
      t1.accounttype = 1          AND
      t1.usertype = 'INDIVIDUAL'  AND
      t2.documentid IS NULL

答案 1 :(得分:1)

试试这个:

SELECT distinct documentcategory,documentcategoryid
FROM  tbldocumentmaster m
LEFT OUTER JOIN tbldocumentbyclient d on d.documentid = m.documentid 
where accounttype = 1 and usertype= 'INDIVIDUAL'
and m.documentid is null 
and applicationid = '000116'
group by documentcategory,documentcategoryid
order by documentcategoryid;

答案 2 :(得分:0)

我还没有测试,但您可以尝试此查询:

SELECT  documentcategory,documentcategoryid, string_agg(documentid::text, ',')   as documentid
                        FROM  tbldocumentmaster 
                        where accounttype = 1 and usertype= 'INDIVIDUAL' and documentid not in (select documentid from tbldocumentbyclient where tbldocumentbyclient.isactive = true and applicationid = '000116')
                        group by documentcategory,documentcategoryid
                        order by documentcategoryid;