SQL:按父字段的子查询过滤器

时间:2016-03-31 05:06:56

标签: sql amazon-redshift

我有以下SQL查询,我无法开始工作。

数据架构

| Timestamp                | Status   | Amount |
|--------------------------|----------|--------|
| 2016-03-23T08:03:34.204Z | Approved |   100  |
| 2016-03-23T16:00:06.755Z | Declined |   450  |
| 2016-03-30T10:18:43.846Z | Approved | 50010  |

期望输出

| Date       | Approved Count | Declined Count |
|------------|----------------|----------------|
| 2016-03-23 | 1              | 1              |
| 2016-03-30 | 1              | 0              |

我尝试了什么

SELECT DATE(timestamp) AS Date,

  (SELECT COUNT(*)
   FROM db.transactions
   WHERE status='Approved'
     AND DATE(timestamp)=Date) AS Approved,

  (SELECT COUNT(*)
   FROM db.transactions
   WHERE status='Declined') AS Declined
FROM db.transactions a
GROUP BY Date;

..失败并显示错误消息:

  

Amazon Redshift发生错误。列“日期”不存在

2 个答案:

答案 0 :(得分:1)

您获得的错误是尝试使用SELECT子句中GROUP BY子句中定义的列别名,别名不可用,因为GROUP BY实际上已经处理过SELECT。您可以使用GROUP BY DATE(timestamp)来消除错误,但这可以通过条件聚合更有效地完成:

SELECT DATE(timestamp) AS Date
      ,SUM(CASE WHEN status='Approved' THEN 1 ELSE 0 END) AS Approved
      ,SUM(CASE WHEN status='Declined' THEN 1 ELSE 0 END) AS Declined
FROM db.transactions
GROUP BY  DATE(timestamp)

答案 1 :(得分:0)

    SELECT DATE(timestamp),

  (SELECT COUNT(*)
   FROM db.transactions
   WHERE status='Approved'
     AND DATE(timestamp) AS Approved,

  (SELECT COUNT(*)
   FROM db.transactions
   WHERE status='Declined') AS Declined
FROM db.transactions GROUP BY Date;