我知道您可以在本月初将@Date设置为01/01/2001
。
,然后调用每个月初的日期,例如:
01/01/2001
01/02/2001
01/03/2001
但是,如果可能的话,我该如何总是找到该月中旬的日期?我会用15号,但您遇到的是2月
我需要对月中的销售总额进行分析
任何想法请团队合作
答案 0 :(得分:2)
您可以使用此公式
DECLARE @Date DATE ='20180201'
SELECT DATEADD(DAY, (DAY(EOMONTH(@Date)) / 2) - 1, @Date)
答案 1 :(得分:0)
解决方案:
获取月份中的天数并计算“中间”天。在下一个示例中,天数(28、29、30或31)除以整数除数(2),因此结果将是一个整数,该整数的任何小数部分都会被截断。选择您喜欢的方法。
DECLARE @date date
SET @date = DATEFROMPARTS(2020, 2, 1)
-- 15 is the half of the month with 30 and 31 days, 14 for months with 28, 29 days
SELECT DATEDIFF(d, @date, DATEADD(month, 1, @date)) / 2
-- 16 is the half of the month with 31 days, 15 for months with 29, 30 days, 14 for month with 28 days
SELECT (DATEDIFF(d, @date, DATEADD(month, 1, @date)) + 1) / 2
示例:
WITH Months AS
(
SELECT SomeDate = DATEFROMPARTS(2018, 1, 1)
UNION ALL
SELECT DATEADD(month, 1, SomeDate)
FROM Months
WHERE DATEPART(month, SomeDate) < 12
)
SELECT
SomeDate AS FirstDate,
DATEADD(d, -1, DATEADD(month, 1, SomeDate)) AS LastDate,
DATEDIFF(d, SomeDate, DATEADD(month, 1, SomeDate)) AS DaysBetween,
DATEDIFF(d, SomeDate, DATEADD(month, 1, SomeDate)) / 2 AS HalfOfMonth1,
(DATEDIFF(d, SomeDate, DATEADD(month, 1, SomeDate)) + 1) / 2 AS HalfOfMonth2
FROM Months
输出:
FirstDate LastDate DaysBetween HalfOfMonth1 HalfOfMonth2
01/01/2018 31/01/2018 31 15 16
01/02/2018 28/02/2018 28 14 14
01/03/2018 31/03/2018 31 15 16
01/04/2018 30/04/2018 30 15 15
01/05/2018 31/05/2018 31 15 16
01/06/2018 30/06/2018 30 15 15
01/07/2018 31/07/2018 31 15 16
01/08/2018 31/08/2018 31 15 16
01/09/2018 30/09/2018 30 15 15
01/10/2018 31/10/2018 31 15 16
01/11/2018 30/11/2018 30 15 15
01/12/2018 31/12/2018 31 15 16
答案 2 :(得分:0)
我尝试了以下
SELECT DATEADD(dd, (datediff(DD, DATEADD(m, DATEDIFF(m, 0, GETDATE()), - 1), eomonth(getdate())) / 2), DATEADD(m, DATEDIFF(m, 0, GETDATE()), - 1)),
CEILING((datediff(DD, DATEADD(m, DATEDIFF(m, 0, GETDATE()), - 1), eomonth(getdate())) / 2.00))
的更新
DECLARE @Date DATE ='2018-10-01'---'20180201'
SELECT DATEADD(DAY, CEILING((DAY(EOMONTH(@Date)) / 2.00)) - 1, @Date)
答案 3 :(得分:0)
假设您想要的日期更接近月初或月末(14代表28,15代表29 / 30,16代表31天),只需使用数字除法和上限函数即可:
SELECT
testdate,
DAY(EOMONTH(testdate)),
DATEADD(DAY, CEILING(DAY(EOMONTH(testdate)) / 2.0) - 1, testdate)
FROM (VALUES
('2001-02-01'),
('2000-02-01'),
('2000-04-01'),
('2000-03-01')
) AS v(testdate)
结果:
2001-02-01 | 28 | 2001-02-14
2000-02-01 | 29 | 2000-02-15
2000-04-01 | 30 | 2000-04-15
2000-03-01 | 31 | 2000-03-16
答案 4 :(得分:0)
这是一个查询,该查询通过使用datediff获取月份的开始日期和月份的结束日期,您可以找到要添加和减去的天数
Set @tdate = '02/10/2018';
Select DATEFROMPARTS(YEAR(@tdate),MONTH(@tdate),1) as startdate , dateadd(day,-1,DATEFROMPARTS(YEAR(@tdate),MONTH(@tdate)+1,1)) as enddate
致谢