sqlserver按年月日分组
时间: 2023-07-24 21:05:24 浏览: 107
在 SQL Server 中,你可以使用 `GROUP BY` 和 `DATEPART` 函数来按年月日分组。例如,如果你有一个名为 `orders` 的表,其中包含一个名为 `order_date` 的日期类型的列,你可以按照以下方式按年月日分组:
按年份分组:
```
SELECT DATEPART(year, order_date) as year, COUNT(*) as num_orders
FROM orders
GROUP BY DATEPART(year, order_date)
```
按月份分组:
```
SELECT DATEPART(year, order_date) as year, DATEPART(month, order_date) as month, COUNT(*) as num_orders
FROM orders
GROUP BY DATEPART(year, order_date), DATEPART(month, order_date)
```
按天数分组:
```
SELECT DATEPART(year, order_date) as year, DATEPART(month, order_date) as month, DATEPART(day, order_date) as day, COUNT(*) as num_orders
FROM orders
GROUP BY DATEPART(year, order_date), DATEPART(month, order_date), DATEPART(day, order_date)
```
这些查询将分别按年份、月份和天数对 `orders` 表进行分组,并计算每个组中的订单数。
阅读全文