返回重复值Postgresql查询

时间:2016-10-16 05:16:33

标签: sql postgresql join left-join

    with
 cte1 as(
    select sts.user_id,u.username,sts.target,sts.from_date,sts.to_date
    from sales_target_settings sts
    left join users u on sts.user_id=u.id
    order by sts.id
            ),
     cte2 as (
            select count(*) as tot,se.assign_to_id 
    from sales_enquiry se
    left join cte1 on se.assign_to_id=cte1.user_id 
    where se.enq_date between cte1.from_date and cte1.to_date
    group by se.assign_to_id)  

    select cte1.user_id,cte1.username,cte1.target,cte1.from_date,cte1.to_date,coalesce(cte2.tot,0) as total,case when (cte1.target-coalesce(cte2.tot,0))>0 then cte1.target-coalesce(cte2.tot,0) else 0 end as balance
    from cte1 left join cte2 on cte1.user_id=cte2.assign_to_id
    order by cte1.username ;

OUTPUT OUTPUT

第一个表sales_target_settings' columns user_id 目标, from_date , to_date`

第二个表sales_enquiryenq_dateassign_to_id

我希望每个用户的总查询次数来自表sales_target_settings中from_date和to_date之间的查询日期。

从用户ID 111的输出中,总值为6。实际上,2016-10-012016-10-31之间的日期是用户111 6的总价值是正确的,但2016-09-012016-09-30总值之间的日期是{ {1}}。如何解决这个问题。我认为查询没有检查用户0的{​​{1}}到2016-09-01之间的日期

1 个答案:

答案 0 :(得分:1)

查看sql查询后,这是我的观察

with cte1 as(
select sts.user_id,u.username,sts.target,sts.from_date,sts.to_date
from sales_target_settings sts
left join users u on sts.user_id=u.id
order by sts.id ),

 ------------------------------------------- this cte1 is returning two rows with two different from_date and to_date for userid = 111
 cte2 as (
        select count(*) as tot,se.assign_to_id , 
-------------------------------------------- add cte1.from_date, cte1.to_date to cte2
        cte1.from_date, cte1.to_date
-------------
from sales_enquiry se
left join cte1 on se.assign_to_id=cte1.user_id 
where se.enq_date between cte1.from_date and cte1.to_date
group by se.assign_to_id,cte1.from_date, cte1.to_date)  

-------------------------------------------- this cte2 is returning one row for 111

select cte1.user_id,cte1.username,cte1.target,cte1.from_date,cte1.to_date,coalesce(cte2.tot,0) as total,case when (cte1.target-coalesce(cte2.tot,0))>0 then cte1.target-coalesce(cte2.tot,0) else 0 end as balance
from 

------------------------------------------ You are joining cte1 and cte2 only the basis of user_id. Instead of doing that add two more condition two join those cte1 and cte2
cte1 
left join cte2 on 
cte1.user_id=cte2.assign_to_id
and cte1.from_date = cte2.from_date
and cte1.to_date = cte2.to_date

order by cte1.username ;