SQL 从 Year 和 Quarter 创建一个 DateTime 值

SQL create a DateTime value from Year and Quarter(SQL 从 Year 和 Quarter 创建一个 DateTime 值)
本文介绍了SQL 从 Year 和 Quarter 创建一个 DateTime 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我知道与日程相关的里程碑的年份和季度(例如2010"和4"),我想从中选择/创建日期时间.有许多漂亮的方法可以用特定日期的格式(qq")来识别季度,但不能反过来(或者有吗?).这是使用 t-sql/SQL Server.

I know the year and the quarter (e.g. "2010" and "4") for a schedule-related milestone and I want to select/create a datetime from it. There are a number of nifty ways to identify the quarter with formats ("qq") of a particular date, but not to go the other way around (or are there?). This is with t-sql / SQL Server.

注意:日期时间应为该季度的最后天.

Note: the datetime should be for the last day of that quarter.

更新:这是我最终使用 gbn 提供的解决方案,带有 AaronLS 的变量名称,然后根据 Frank Kalis 的建议进行了缩短和改进:-) 对所有 4 个季度进行测试非常重要确保这一年得到妥善处理.感谢所有回答的人!

DECLARE @TheQuarter INT
DECLARE @theYear INT
-- Note: qq = q = quarter for the datepart
SET @TheQuarter = 1
SET @TheYear = 2011
SELECT DATEADD(YEAR, @TheYear-1900, DATEADD(qq, @TheQuarter, -1))
-- 2011-03-31 00:00:00.000

SET @TheQuarter = 2
SET @TheYear = 2011
SELECT DATEADD(YEAR, @TheYear-1900, DATEADD(qq, @TheQuarter, -1))
-- 2011-06-30 00:00:00.000

SET @TheQuarter = 3
SET @TheYear = 2011
SELECT DATEADD(YEAR, @TheYear-1900, DATEADD(qq, @TheQuarter, -1))
-- 2011-09-30 00:00:00.000

SET @TheQuarter = 4
SET @TheYear = 2011
SELECT DATEADD(YEAR, @TheYear-1900, DATEADD(qq, @TheQuarter, -1))
-- 2011-12-31 00:00:00.000

以下是一些从日期中获取季度但不是相反的 q:计算当前季度的最后一天;计算季度的最后一天;在 SQL Server 中存储季度和年度的最佳方式?

Here are a few q's that fetch the quarter from the date but not the other way around: Calculate the Last Day in the CURRENT quarter; Calculate the last day of the quarter; Best way to store quarter and year in SQL Server?

推荐答案

永远不要使用字符串进行日期时间转换:格式、语言等错误太多了.

Never use strings for datetime conversions: too much to go wrong with formats, language etc.

保持在日期时间类型...

Keep it in the datetime type...

Select dateadd(day, -1, 
                       dateadd(year, @year-1900,
                                          dateadd(quarter, @qq, 0)
                                     )
             )

这篇关于SQL 从 Year 和 Quarter 创建一个 DateTime 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)