【问题标题】:sql not showing null values in between querysql在查询之间不显示空值
【发布时间】:2016-04-26 15:08:25
【问题描述】:

我正在使用 postgres,我有一个查询来显示两个日期之间的销售代表的一些数据,但我还需要显示那些没有销售的数据,我有这个:

    SELECT SALESREP.SALESREPID, COALESCE(SUM(ORDERLINE.QUANTITY),0) AS TOTALSALES, COALESCE(SUM(ORDERLINE.QUANTITY*ORDERLINE.UNITSELLINGPRICE),0) AS TOTALVALUE
FROM SHOPORDER
right JOIN SALESREP ON SALESREP.SALESREPID = SHOPORDER.SALESREPID 
left  JOIN ORDERLINE ON ORDERLINE.SHOPORDERID=SHOPORDER.SHOPORDERID
WHERE
SHOPORDER.ORDERDATE BETWEEN '2010-01-01' AND '2016-04-30' or SHOPORDER.ORDERDATE is null
GROUP BY SALESREP.SALESREPID
ORDER BY TOTALVALUE desc

它给了我以下结果:

3;7;287.00
2;9;190.88
1;6;147.00
4;1;59.00
5;0;0

但是当我尝试将日期设置为 2017 年时,它只出现在第五行。 有没有办法让所有 5 行都显示为 0 或根本不显示,因为 2017 年没有销售代表有销售?

谢谢

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    在我看来,您希望使用 CASE 语句:

    http://www.postgresql.org/docs/current/static/functions-conditional.html

    例子:

    postgres=# create table t (x int );
    CREATE TABLE
    postgres=# insert into t values (1);
    INSERT 0 1
    postgres=# insert into t values (NULL);
    INSERT 0 1
    postgres=# insert into t values (3);
    INSERT 0 1
    postgres=# select * from t;
     x
    ---
     1
    
     3
    (3 rows)
    
    postgres=# select (CASE WHEN x is NULL THEN 0 ELSE x END) from t;
     x
    ---
     1
     0
     3
    (3 rows)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多