这对你们所有人都很奇怪。
我需要确定一个月内的天数
;WITH cteNetProfit AS
(
---- NET PROFIT
SELECT DT.CreateDate
, SUM(DT.Revenue) as Revenue
, SUM(DT.Cost) as Cost
, SUM(DT.GROSSPROFIT) AS GROSSPROFIT
FROM
(
SELECT CAST([createDTG] AS DATE) as CreateDate
, SUM(Revenue) as Revenue
, SUM(Cost) as Cost
, SUM(REVENUE - COST) AS GROSSPROFIT
FROM [dbo].[CostRevenueSpecific]
WHERE CAST([createDTG] AS DATE) > CAST(GETDATE() - 91 AS DATE)
AND CAST([createDTG] AS DATE) <= CAST(GETDATE() - 1 AS DATE)
GROUP BY createDTG
UNION ALL
SELECT CAST([CallDate] AS DATE) AS CreateDate
, SUM(Revenue) as Revenue
, SUM(Cost) as Cost
, SUM(REVENUE - COST) AS GROSSPROFIT
FROM abc.PublisherCallByDay
WHERE CAST([CallDate] AS DATE) > CAST(GETDATE() - 91 AS DATE)
AND CAST([CallDate] AS DATE) <= CAST(GETDATE() - 1 AS DATE)
GROUP BY CALLDATE
) DT
GROUP BY DT.CreateDate
)
select distinct MONTH(CREATEDATE), DateDiff(Day,CreateDate,DateAdd(month,1,CreateDate))
FROM cteNetProfit
由于某种原因,它返回2016年3月份的两个不同结果,一个结果是30,另一个结果是31(当然是正确的)我验证基础数据只有31天的数据游行。由于2月是闰年,这会影响DATEDIFF功能。剩下的几个月会返回正确的#。
2 29
3 31
3 30
4 30
5 31
答案 0 :(得分:0)
当您达到2016-03-31日期时,差异就会出现。如果您在2016-03-30和2016-03-31运行以下查询,则在两个实例中使用DATEADD添加1个月的结果为2016-04-30。它返回下个月的最后一天。
SELECT DATEADD(MONTH,1,'2016-03-30') , DATEADD(MONTH,1,'2016-03-31')
这种语法似乎有效(由https://raresql.com/2013/01/06/sql-server-get-number-of-days-in-month/提供)。
SELECT DAY(DATEADD(ms,-2,DATEADD(MONTH, DATEDIFF(MONTH,0,@DATE)+1,0))) AS [Current Month]
答案 1 :(得分:0)
感谢您的投入,但我在其他地方找到了解决方案
select Distinct MONTH(CREATEDATE), Day(EOMONTH(CreateDate))
FROM cteNetProfit