简体   繁体   English

有没有其他方法可以从日期中提取年份?

[英]Is there a different way to extract the year from a date?

This code works on Google's Cloud SQL.此代码适用于 Google 的 Cloud SQL。 I was wondering what the equivalent is or another way to query it on Microsoft SQL Server 2019. When I use this same code I get the error "'Extract' is not a recognized built-in function name.我想知道在 Microsoft SQL Server 2019 上查询它的等价物是什么或另一种方式。当我使用相同的代码时,我收到错误“'Extract'不是可识别的内置 function 名称。

SELECT DATEPART(year, [starttime]) as trip_year,    
       COUNT(*) as trip_count
FROM [dbo].[BikeTripData]
WHERE [starttime] BETWEEN '2014-01-01T00:00:00'
   AND '2015-12-31T23:59:59'
   AND [bikeid] is not null
GROUP BY 1

UPDATE: I've tried this code with DATEPART however I still get the error message "Each GROUP BY expression must contain at least one column that is not an outer reference."更新:我已经使用 DATEPART 尝试了此代码,但是我仍然收到错误消息“每个 GROUP BY 表达式必须包含至少一个不是外部引用的列。”

Without the GROUP BY function I get "Column 'dbo.BikeTripData.starttime' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."如果没有 GROUP BY function 我得到“列 'dbo.BikeTripData.starttime' 在 select 列表中无效,因为它不包含在聚合 ZC1C425268E687YA 子句或 BGROUP 子句中。”

For preference I'm trying to create 2 columns of trip_year and trip_count where it would show the year followed by the trip count.出于偏好,我正在尝试创建 2 列 trip_year 和 trip_count ,其中将显示年份和旅行次数。

In Sql-Server you can use YEAR :Sql-Server 中,您可以使用YEAR

   select year(starttime)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM