我試圖確定根據CreateDate
場每個月的週末天數。數的週末每月
當月有31天的時候,我目前的努力似乎已經停止了1天。
任何人都可以解釋爲什麼這是怎麼回事?
;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 [dbo].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),
A1
AS (SELECT DISTINCT
MONTH(CREATEDATE) AS MONTHNO
, DAY(EOMONTH(CreateDate)) AS DaysinMth
FROM cteNetProfit),
A2
AS (
SELECT A.MONTHNO
, COUNT(A.WorkDay) AS DAYSPERMTH
, A.WorkDay
FROM
(SELECT MONTH(CREATEDATE) AS MONTHNO
, CHOOSE
(DATEPART(dw, CreateDate), 'WEEKEND', 'Weekday', 'Weekday', 'Weekday', 'Weekday', 'Weekday', 'WEEKEND') AS WorkDay
FROM cteNetProfit) A
WHERE A.WORKDAY = 'WEEKEND'
GROUP BY A.MONTHNO
, A.WorkDay
UNION
SELECT A.MONTHNO
, COUNT(A.WorkDay) AS DAYSPERMTH
, A.WorkDay
FROM
(SELECT MONTH(CREATEDATE) AS MONTHNO
, CHOOSE
(DATEPART(dw, CreateDate), 'WEEKEND', 'Weekday', 'Weekday', 'Weekday', 'Weekday', 'Weekday', 'WEEKEND') AS WorkDay
FROM cteNetProfit) A
WHERE A.WORKDAY = 'WEEKDAY'
GROUP BY A.MONTHNO
, A.WorkDay),
A3
AS (SELECT A1.MONTHNO
, A1.DaysinMth
, A2.DAYSPERMTH
, A2.WorkDay
, CASE
WHEN A2.WorkDay = 'WEEKEND' THEN SUM(A2.DAYSPERMTH)/2
ELSE A2.DAYSPERMTH
END AS DP_REV
FROM a1
INNER JOIN A2 ON A1.MONTHNO = A2.MONTHNO
GROUP BY A1.MONTHNO
, A1.DaysinMth
, A2.DAYSPERMTH
, A2.WorkDay),
A4
AS (SELECT A3.MONTHNO
, A3.DAYSINMTH
, SUM(A3.DP_REV) AS DPREV
-- , A3.DP_REV
FROM A1
INNER JOIN A3 ON A1.MONTHNO = A3.MONTHNO
GROUP BY A3.MONTHNO
, A3.DaysinMth)
SELECT A1.MONTHNO
, A1.DAYSINMTH
, A4.DPREV
, A3.DP_REV
, A3.DAYSPERMTH
FROM A1
, A3
, A4
WHERE A1.MONTHNO = A4.MONTHNO
AND A1.MONTHNO = A3.MONTHNO;
正如你可以看到突出顯示的數字在一個月不等於總天數做。
的硬類跟隨你的查詢,但你有沒有考慮數着日子'WHERE DATEPART(平日,[YourDate])NOT IN(0,1)和'在你的月份組? – scsimon
你應該建立一個date_dim表,這個表有周末標誌。這是我的最愛,但有一堆:[date_dim鏈接](https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server /) – Matt