Postgres - 功能计数

时间:2014-12-02 15:12:11

标签: postgresql count

Thare是两张桌子:

select "PRD_ID", "PRD_AUDIT_RD", "PRS_ID", "PRS_AUDIT_RD" from lct_products 
left outer join lct_prd_properties on "PRD_ID" = "PRS_PRD_ID"
where "PRD_AUDIT_RD" is null

结果:

 "PRD_ID", "PRD_AUDIT_RD", "PRS_ID", "PRS_AUDIT_RD"
 18;"";57;"2014-09-15 22:48:37.39"
 18;"";60;"2014-09-16 17:40:32.016"
 18;"";71;"2014-09-19 22:00:31.289"
 18;"";72;"2014-10-16 23:35:50.125"
 18;"";58;"2014-10-17 11:23:51.643"
 11;"";83;"2014-12-02 13:41:19.503"
 11;"";82;"2014-12-02 13:42:09.677"
 18;"";59;"2014-12-02 13:44:23.22"
 14;"";85;"2014-12-02 13:53:00.428"
 14;"";84;"2014-12-02 13:58:12.492"
 14;"";87;"2014-12-02 14:09:21.304"
 14;"";86;"2014-12-02 14:15:15.236"
 25;"";;""
 17;"";;""
 37;"";;""
 28;"";;""
 30;"";;""
 16;"";;""
 36;"";;""
 35;"";;""

我需要列出所有产品ID和计算分配给每个产品的属性数量。 PRS_AUDIT_RD列中的日期是先前为特定产品分配的属性被逻辑删除。因此,对于ID = 18的产品,我希望在列表中也包含当前为其分配0个属性的信息。

以下查询无法解决问题,因为它未考虑列PRS_AUDIT_RD:

select "PRD_ID", count("PRS_ID")  from (
   select "PRD_ID", "PRD_AUDIT_RD", "PRS_ID", "PRS_AUDIT_RD" from lct_products 
   left outer join lct_prd_properties on "PRD_ID" = "PRS_PRD_ID"
   where "PRD_AUDIT_RD" is null
) xx group by "PRD_ID" 

但如果我在PRS_AUDIT_RD上添加条件,我将不会获得ID = 18的产品:

select "PRD_ID", count("PRS_ID")  from (
    select "PRD_ID", "PRD_AUDIT_RD", "PRS_ID", "PRS_AUDIT_RD" from lct_products 
    left outer join lct_prd_properties on "PRD_ID" = "PRS_PRD_ID"
    where "PRD_AUDIT_RD" is null
    and "PRS_AUDIT_RD" is null
) xx group by "PRD_ID"

你知道如何做到这一点吗?

此致 米甲

1 个答案:

答案 0 :(得分:0)

您必须将PRS_AUDIT_RD IS NULL子句置于加入条件中,以使其保持LEFT JOIN,从而返回ID=18

SELECT
  p.PRD_ID,
  p.PRD_AUDIT_RD,
  COUNT(pp.*)
FROM
  lct_products p LEFT JOIN lct_prd_properties pp
ON
  p.PRD_ID = pp.PRS_PRD_ID AND pp.PRS_AUDIT_RD IS NULL
WHERE
  p.PRD_AUDIT_RD IS NULL
GROUP BY
  p.PRD_ID;