当没有匹配的数据而不是返回0行时,有没有方法返回一个带0的列?

dwbf0jvd  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(282)

我有这个问题。

SELECT  
  FACTORY,  
  SUBSTR(dt,1,20 ) AS 'DATE',  
  SUM(count_a) AS 'PRODUCT A',  
  SUM(count_b) AS 'PRODUCT B', 
  SUM(count_a + count_b) AS 'TOTAL' 
FROM LIST 
WHERE DATE BETWEEN '2018-12-01' AND '2018-12-05'
GROUP BY COUNTRY, SUBSTR(dt,1,20)
ORDER BY COUNTRY, SUBSTR(dt,1,20);

“2018-12-03”中没有匹配数据
所以它的返回值是这样的

FACTORY   |    DATE    |   PRODUCT A |  PRODUCT B |  TOTAL
-------------------------------------------------------------
Factory_A | 2018-12-01 |         5000|      10000 |   15000
Factory_A | 2018-12-02 |        10000|       5000 |   15000
Factory_A | 2018-12-04 |        10000|      10000 |   20000
Factory_A | 2018-12-05 |        15000|       5000 |   20000

但当没有行与上述条件匹配时,我希望它返回0。
这样地

FACTORY |     DATE     | PRODUCT A | PRODUCT B |   TOTAL
----------------------------------------------------------
Factory_A | 2018-12-01 |       5000|     10000 |   15000 
Factory_A | 2018-12-02 |      10000|      5000 |   15000

**Factory_A | 2018-12-03 |          0|          0|       0**

Factory_A | 2018-12-04 |      10000|      10000|   20000
Factory_A | 2018-12-05 |      15000|       5000|   20000

在mysql中,有没有什么方法可以在一列中输入0而不是返回0行?

vsdwdz23

vsdwdz231#

你可以考虑使用右外连接。
对于这个解决方案,你需要有一个日历表,其中包含所有的日期。

SELECT  
  FACTORY,  
  SUBSTR(Calendar.Date,1,20 ) AS 'DATE',  
  SUM(count_a) AS 'PRODUCT A',  
  SUM(count_b) AS 'PRODUCT B', 
  SUM(count_a + count_b) AS 'TOTAL' 
FROM LIST 
RIGHT OUTER JOIN CALENDAR ON list.dt = Calendar.Date
WHERE DATE BETWEEN '2018-12-01' AND '2018-12-05'
GROUP BY COUNTRY, SUBSTR(dt,1,20)
ORDER BY COUNTRY, SUBSTR(dt,1,20);

相关问题