在sql计数中显示零

时间:2016-12-16 14:22:55

标签: sql amazon-redshift

我正在使用红移并尝试按天计算不同的东西,但是当表2中的计数为零时它没有显示。如何让它显示为零?

SELECT TO_CHAR(date1,'dd') AS day,
       COUNT(*) as Volume,sum(CASE WHEN status = 'ANSWERED' THEN 1 ELSE 0 END )as ANSWERED , t2.Volume AS TRANSFERS
FROM table1 t1
  RIGHT JOIN (SELECT TO_CHAR(date2,'dd') AS day,
                     COUNT(*) as Volume
              FROM table2
              WHERE TO_CHAR(date2,'yyyy_MM') IN (SELECT DISTINCT TO_CHAR(date2,'yyyy_MM')
                                                FROM table2
                                                WHERE date2 BETWEEN DATE ('2016-11-01') AND DATE ('2016-12-30'))
              AND   type = 'Active'
              GROUP BY day) t2 ON  TO_CHAR(date1,'dd') = day
WHERE TO_CHAR(date1,'yyyy_MM') IN (SELECT DISTINCT TO_CHAR(date1,'yyyy_MM')
                                             FROM table1
                                             WHERE date1 BETWEEN DATE ('2016-11-01') AND DATE ('2016-12-30'))
GROUP BY 1,4
ORDER BY 1

1 个答案:

答案 0 :(得分:0)

请注意,您在表之间使用了正确的连接。这意味着第一个表中没有第二个表中匹配日的任何行都不会显示。 If you're new with SQL joins you can refer to this image that explains it.

如果您的第一个(或左表)包含应该显示在结果中的所有唯一日期,只需切换"右键"到了"左边"加入。