尽管脚本仅包含每周数据,但我正在尝试按日期对数据进行排序。
下面是一个示例SQL:
SELECT
CONCAT(CONCAT('Week', ''),
EXTRACT(WEEK FROM sale_date ::date + '1 day'::interval)
),
COUNT(*)
FROM sales
WHERE sale_date between '2018-12-29' AND '2019-01-04'
GROUP BY CONCAT(CONCAT('Week', ''),
EXTRACT(WEEK FROM sale_date ::date + '1 day'::interval)
)
ORDER BY 1 ASC
上面的脚本运行得很好,但是当对最终输出进行排序时,它首先将Week1排序,最后将Week 52排序,而我试图按实际日期排序,使得W52首先出现(自2018-12起),而W1出现。最后。
当前输出:
Week1,101
Week52,2350
预期输出:
Week52,2350
Week1,101
我正在使用Amazon Redshift DB。
答案 0 :(得分:0)
这可以是你行,它需要添加一个额外的列到查询
select date_trunc('WEEK',sale_date ::date + interval '1 day'),
CONCAT(CONCAT('Week', ''),
EXTRACT(WEEK FROM sale_date ::date + '1 day'::interval)),
count(*)
from sales
where sale_date between '2018-12-29' and '2019-01-04'
group by date_trunc('WEEK',sale_date ::date+ interval '1 day'),
CONCAT(CONCAT('Week', ''),
EXTRACT(WEEK FROM sale_date ::date + '1 day'::interval))
order by date_trunc('WEEK',sale_date ::date+ interval '1 day') asc;
答案 1 :(得分:0)
这应该有效:
SELECT week, count FROM (
SELECT week, MAX(sale_date) max_date, COUNT(*) count FROM (
SELECT sale_date,
CONCAT('Week', EXTRACT(WEEK FROM sale_date::date + '1 day'::interval)) AS week
FROM sales
WHERE sale_date between '2018-12-29' AND '2019-01-04'
)
GROUP BY week
) ORDER BY max_date ASC
如果每个空间超过一年,将会得到奇怪的结果。