我尝试使用当前周的数据(总是在变化)创建一个sql表以及上一年的那些日期数据。我有多个表,我必须加入,但不知道如何将它们全部创建到一个表中。以下是我到目前为止的情况:
-------当前年份-------
DECLARE
@CURRENTDATE DATE,
@BEGINDATE DATE
SET @CURRENTDATE = CONVERT(DATE,GETDATE()) ---// TODAY'S DATE //---
SET @BEGINDATE = DATEADD(DAY, -7, GETDATE()) ---// A WEEK BEFORE TODAY'S DATE //---
SELECT SALES.*, RECRUITS.Recruits
FROM
(
SELECT
CONVERT(VARCHAR(10), A.[ORDER DATE], 101) AS 'DAY'
, 'Sales Revenue Current Year' = FORMAT(SUM(A.[GRAND TOTAL]) ,'C', 'EN-US')
, 'Comm. Sales Volume Current Year' = FORMAT(sum(a. [QUALIFYING VOLUME]), 'C', 'EN-US')
FROM TABLE1 a
WHERE CONVERT(VARCHAR(10), A.[ORDER DATE], 101) >= @BEGINDATE AND CONVERT(VARCHAR(10), A.[ORDER DATE], 101) < @CURRENTDATE
GROUP BY CONVERT(VARCHAR(10), A.[ORDER DATE], 101)
) SALES,
(
SELECT
CONVERT(VARCHAR(10),a.[start date],101) AS 'DAY'
,count(b.[id number]) as Recruits
from TABLE2 a
left join
TABLE3 b
on a.enroller = b. [id number]
WHERE CONVERT(VARCHAR(10), A.[START DATE], 101) >= @BEGINDATE AND CONVERT(VARCHAR(10), A.[START DATE], 101) < @CURRENTDATE
group by a.[start date]
) RECRUITS
WHERE SALES.DAY = RECRUITS.DAY
我上一年的脚本相同。除了我将日期设置为-366和-373天之外,它是相同的。任何帮助都会很棒!
答案 0 :(得分:0)
您可以使用带有“OR”的多个日期,如下所示,但更好的解决方案是使用日期维度表,每个日期日期的列表,例如“WeekOfYear”,“WeekOfMonth”,“QuarterOfYear” ,“IsHoliday”等。然后你可以加入你对象的日期并查询“t1.WeekOfYear = t2.WeekOfYear”。
DECLARE
@EndDate DATE = GETDATE() ---// TODAY'S DATE //---
, @StartDate DATE = DATEADD(DAY, -7, GETDATE()) ---// A WEEK BEFORE TODAY'S DATE //---
, @LYStartDate DATE = DATEADD(YEAR, -1, GETDATE()) ---// A YEAR BEFORE TODAY'S DATE //---
, @LYEndDate DATE = DATEADD(DAY, -7, DATEADD(YEAR, -1, GETDATE())) ---// A YEAR AND A WEEK BEFORE TODAY'S DATE //---
SELECT SALES.*, RECRUITS.Recruits
FROM
(
SELECT
'DAY' = CONVERT(VARCHAR(10), A.[ORDER DATE], 101)
, 'Sales Revenue Current Year' = FORMAT(SUM(A.[GRAND TOTAL]) ,'C', 'EN-US')
, 'Comm. Sales Volume Current Year' = FORMAT(sum(a. [QUALIFYING VOLUME]), 'C', 'EN-US')
FROM TABLE1 a
WHERE (
(CAST(A.[ORDER DATE] AS DATE) >= @StartDate AND CAST(A.[ORDER DATE] AS DATE) <= @EndDate)
OR
(CAST(A.[ORDER DATE] AS DATE) >= @LYStartDate AND CAST(A.[ORDER DATE] AS DATE) <= @lyEndDate)
)
GROUP BY CAST(A.[ORDER DATE] AS DATE)
) SALES,
(
SELECT
'DAY' = CAST(a.[start date] AS DATE)
, Recruits = COUNT(b.[id number])
FROM TABLE2 a
LEFT JOIN TABLE3 b
ON a.enroller = b. [id number]
WHERE (
(CAST(A.[START DATE] AS DATE) >= @StartDate AND CAST(A.[ORDER DATE] AS DATE) <= @EndDate)
OR
(CAST(A.[START DATE] AS DATE) >= @lyStartDate AND CAST(A.[ORDER DATE] AS DATE) <= @LYEndDate)
GROUP BY CAST(a.[start date] AS DATE)
) RECRUITS
WHERE SALES.DAY = RECRUITS.DAY