SQL Count 按天分组
Posted
技术标签:
【中文标题】SQL Count 按天分组【英文标题】:SQL Count group by days 【发布时间】:2021-05-10 09:56:39 【问题描述】:我有兴趣了解从一些示例数据中获取包裹所需的不同长度。我目前正在使用此代码:
SELECT COUNT(*)
FROM orders_table
WHERE DATEDIFF(day, order_date, delivered_date) = 2
AND order_date BETWEEN '2021-01-01' AND '2021-01-31'
我想获取不同长度的交付计数,在上面的示例中,它查看了需要 2 天的交付数量。然而,这非常耗时,因为我需要在不同的天数内不断更改 where 语句并重新运行代码,是否有办法对其进行分组并按月分组?所以输出看起来像这样:
January February March April
2D 3D 4D 2D 3D 4D 2D 3D 4D 2D 3D 4D
--------------------------------------------------------------------
12 7 32 21 53 33 8 22 41 9 44 30
【问题讨论】:
【参考方案1】:这并不完全以您想要的格式提供输出,但结果似乎正是您想要的。 通过 DATEDIFF 函数进行分组:
SELECT DATEDIFF(day, order_date, delivered_date) AS Date_Diff, COUNT(*)
FROM orders_table
WHERE order_date BETWEEN '2021-01-01' AND '2021-01-31'
GROUP BY DATEDIFF(day, order_date, delivered_date)
如果您只需要特定的日期差异天数(例如,如果您想查看订单和交付日期仅相差 2、3 和 4 天的订单),那么只需在过滤器中添加您想要的数字:
WHERE DATEDIFF(day, order_date, delivered_date) IN (2, 3, 4)
【讨论】:
【参考方案2】:您的问题包括月份。为此:
SELECT DATE_TRUNC('month', order_date) as yyyymm
DATEDIFF(day, order_date, delivered_date) as days_diff,
COUNT(*)
FROM orders_table
GROUP BY DATE_TRUNC('month', order_date), DATEDIFF(day, order_date, delivered_date);
您可以使用条件聚合来透视这些结果:
SELECT DATEDIFF(day, order_date, delivered_date) as days_diff,
SUM( (DATE_PART(month, order_date) = 1)::INT ) as jan,
SUM( (DATE_PART(month, order_date) = 2)::INT ) as feb,
SUM( (DATE_PART(month, order_date) = 3)::INT ) as mar,
SUM( (DATE_PART(month, order_date) = 4)::INT ) as apr
COUNT(*)
FROM orders_table
WHERE order_date >= '2021-01-01' AND
order_date < '2021-05-01'
GROUP BY DATEDIFF(day, order_date, delivered_date);
【讨论】:
以上是关于SQL Count 按天分组的主要内容,如果未能解决你的问题,请参考以下文章