如果没有销售,则为零

时间:2017-01-05 20:37:02

标签: sql postgresql

我的问题与附件中的问题非常相似,只是我需要在查询中有一个与table1相关的where子句。我的table2(t2)只有一列(名称)而没有日期/时间列,而table1(t1)有name,sales和week。我希望为Sean返回零,因为他在截至01/01/2017的那一周没有任何销售。

Create a third table from two tables

select * from table2:

Names

Maggie
Colleen
Laura
Sean

select * from table1:

Names               Sales                Week
Maggie              1800                 01/01/2017
Colleen             2000                 01/01/2017  
Laura               4000                 01/01/2017
Sean                1500                 12/18/2016   

select t2.Name, coalesce(t1."Employee Sales",0) "Employee Sales"
from emphis t2 left outer join
(select Name, sum(Sales) "Employee Sales"
from empdata
group by Name) t1
on t1.Name = t2.Name

Names              Employee Sales              
Maggie              1800                 
Colleen             2000                 
Laura               4000                 
Sean                1500                   

我正在寻找的结果:

Names              Employee Sales            
Maggie              1800                 
Colleen             2000                 
Laura               4000                 
Sean                 0 

select t2.Name, coalesce(t1."Employee Sales",0) "Employee Sales"
from emphis t2 left outer join
(select Name, sum(Sales) "Employee Sales"
from empdata
group by Name) t1
on t1.Name = t2.Name
where t1.Week = date_trunc('week', now())::date - 1

postgreSQL中的错误:

ERROR:  column t1.Week does not exist
LINE 7: where t1.Week = date_trunc('week', now())::date - 1

我用

where t1.Week = date_trunc('week', now())::date - 1

自动化,所以我不需要更改每个星期日的日期。

2 个答案:

答案 0 :(得分:2)

移动"周"子选择内的条件。这有两个好处:

  1. 如果有人在多个星期内有销售,您将获得该周的部分销售额。
  2. 如果他们没有销售额为$ 0
  3. ,他们会出现在您的列表中

    像这样:

    select t2.Name,
        coalesce(t1."Employee Sales",0) "Employee Sales"
    from emphis t2 
    left outer join (
        select Name, 
            sum(Sales) "Employee Sales"
        from empdata
        where Week = date_trunc('week', now())::date - 1
        group by Name
        ) t1
    on t1.Name = t2.Name
    

答案 1 :(得分:1)

是的,因为您的子查询没有包含或选择Week列。您应该包括该列,例如

(select Name, sum(Sales) "Employee Sales", "Week"
from empdata
group by Name) t1
on t1.Name = t2.Name
where t1.Week = date_trunc('week', now())::date - 1