我有以下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发生错误。列“日期”不存在
答案 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;