将外部分组结果用于' IN'时出现SQL错误子查询中的运算符

时间:2018-03-05 15:23:53

标签: sql postgresql

我有以下查询尝试使用外部聚合结果作为子查询的输入(在这种情况下为in语句):

select 
 COUNT(DISTINCT individual_id) as visitors,
 (select 
   (case when 
     SUM(case when cr2.isConverted = true then 1 else 0 end) > 0 
     then 1 else 0 end) as conv from campaigns_reporting as cr2 where 
     cr2.id in (DISTINCT cr1.id) group by individual_id) as conversions
     from campaigns_reporting as cr1 where
     isinholdback = false  and
    occurredat between '2018-02-25T18:00:00.000Z' and '2018-03-04T17:59:59.000Z' and
    customer_id = '1'
 group by campaign_id, isinholdback

我收到以下错误:

  

错误:语法错误在或附近" DISTINCT"

     

第5行:......来自campaign_reporting为cr2,其中cr2.id为(DISTINCT   C...                                                                ^

注意:我使用的是postgresql。

提前感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:0)

您的查询无法完成。 cr1不能在select id中使用,因为它不包含在group by中。所以试试这个:

select COUNT(DISTINCT individual_id) as visitors, 
   (case when sum(cr3.conv) > 0 then 1 else 0 end) as conversions
   from campaigns_reporting as cr1
   inner join 
   (select id, (case when SUM(case when cr2.isConverted = true then 1 else 0 end) > 0 then 1 else 0 end) as conv 
   from campaigns_reporting  as cr2 
   group by id) as cr3 on cr1.id= cr3.id
where isinholdback = false
and occurredat between '2018-02-25T18:00:00.000Z' and '2018-03-04T17:59:59.000Z'
and customer_id = '1'
group by campaign_id, isinholdback