按月、日统计查询数据SQL、以及case when的使用 -- postgresql、MySQL
在PostgreSQL和MySQL中,您可以使用以下SQL查询来按月、日统计数据,并结合CASE WHEN
子句来进行条件计数。
以下是一个示例,假设我们有一个名为orders
的表,它有一个名为order_date
的日期时间列,我们想要统计每个月中每个星期几的订单数量。
SELECT
EXTRACT(YEAR FROM order_date) AS year,
EXTRACT(MONTH FROM order_date) AS month,
CASE
WHEN EXTRACT(DOW FROM order_date) = 0 THEN 'Sunday'
WHEN EXTRACT(DOW FROM order_date) = 1 THEN 'Monday'
WHEN EXTRACT(DOW FROM order_date) = 2 THEN 'Tuesday'
WHEN EXTRACT(DOW FROM order_date) = 3 THEN 'Wednesday'
WHEN EXTRACT(DOW FROM order_date) = 4 THEN 'Thursday'
WHEN EXTRACT(DOW FROM order_date) = 5 THEN 'Friday'
WHEN EXTRACT(DOW FROM order_date) = 6 THEN 'Saturday'
END AS day_of_week,
COUNT(*) AS order_count
FROM
orders
GROUP BY
year,
month,
day_of_week;
在这个查询中,EXTRACT
函数用于从order_date
字段中提取年份和月份信息,CASE WHEN
用于将DOW值转换为星期名称,然后根据年份、月份和星期名称进行分组并计算每个组中的订单数量。
请注意,在MySQL中,星期是从0(表示周日)到6(表示周六)的,与PostgreSQL中的DOW不同。在MySQL中,您可能需要稍微调整CASE WHEN子句。
对于MySQL,上述查询可能需要稍微调整,如下:
SELECT
YEAR(order_date) AS year,
MONTH(order_date) AS month,
CASE
WHEN DAYOFWEEK(order_date) = 1 THEN 'Sunday'
WHEN DAYOFWEEK(order_date) = 2 THEN 'Monday'
WHEN DAYOFWEEK(order_date) = 3 THEN 'Tuesday'
WHEN DAYOFWEEK(order_date) = 4 THEN 'Wednesday'
WHEN DAYOFWEEK(order_date) = 5 THEN 'Thursday'
WHEN DAYOFWEEK(order_date) = 6 THEN 'Friday'
WHEN DAYOFWEEK(order_date) = 7 THEN 'Saturday'
END AS day_of_week,
COUNT(*) AS order_count
FROM
orders
GROUP BY
year,
month,
day_of_week;
在这个MySQL查询中,YEAR()
和MONTH()
函数用于从日期中提取年份和月份,DAYOFWEEK()
函数返回1到7的数字,代表星期日到星期六,对应于MySQL中的星期。
评论已关闭