sql-server 如何按天对表中的行进行分组?

4nkexdtk  于 2022-10-31  发布在  其他
关注(0)|答案(2)|浏览(181)

我有一个SQL表,其中的列为
| 时间戳记|地区名称|
| - -|- -|
| 2022年10月6日01时00分|东部地区|
| 2022年10月6日03:00:000000|东部地区|
| 2022年10月6日05:00:0000000|西部地区|
| 2022年10月6日01时00分|东部地区|
| 2022年10月7日05:00:0000000|西部地区|
| 2022年10月8日05:00:0000000|东部地区|
| 2022年10月9日01:00:0000000|西部地区|
| 2022年10月9日01:00:0000000|东部地区|
因此,我想按“Day”和“Region”对表进行分组
| 时间戳记|地区名称|计数|
| - -|- -|- -|
| 2022年10月6日|东部地区|三个|
| 2022年10月6日|西部地区|一个|
| 2022年10月7日|西部地区|一个|
| 2022年10月8日|东部地区|一个|
| 2022年10月9日|西部地区|一个|
| 2022年10月9日|东部地区|一个|
所以我用SQL来尝试

SELECT 
[region], 
CONCAT( datepart(YEAR, [Timestamp]), '-',  datepart(MONTH, [Timestamp]), '-', datepart(DAY, [Timestamp])) AS dayEvent,
FROM Table
GROUP BY [region], [dayEvent]

但是我收到错误消息,说“选择列表中的时间戳无效,因为它既没有包含在聚合函数中,也没有包含在GROUP BY子句中。”
你能告诉我怎么解决这个问题吗?

wrrgggsh

wrrgggsh1#

在SQL Server中,您可以通过使用 cross apply 进行简化,该, cross apply* 允许您在 selectgroup by 以及 convert 函数中引用它以提取所需的日期:

select ts [Timestamp], Region, Count(*) [count]
from t
cross apply(values(Convert(Date, [Timestamp])))x(ts)
group by ts, Region;

示例Fiddle

a5g8bdjr

a5g8bdjr2#

我们可以cast(Timestamp as date),这将给予我们想要的结果。

select   cast(Timestamp as date) as Timestamp
        ,Region
        ,count(*)                as count
from     t
group by cast(Timestamp as date), Region

| 时间戳记|地区名称|计数器|
| - -|- -|- -|
| 2022年10月6日|东部地区|三个|
| 2022年10月8日|东部地区|一个|
| 2022年10月9日|东部地区|一个|
| 2022年10月6日|西部地区|一个|
| 2022年10月7日|西部地区|一个|
| 2022年10月9日|西部地区|一个|
Fiddle

相关问题