以下的答案必須假定
A)你想每星期看到一個給定的範圍內,是否有賬戶是在那一週或不訪問。
B)您想查看每週的所有賬戶
C)對於在給定周內訪問的賬戶,請顯示其實際的VisitAction。 D)對於在給定周內未被訪問的賬戶,顯示「未完成」作爲VisitAction。
如果所有這些都是這種情況,那麼以下查詢可能會做你所需要的。有一個正常運作的sqlfiddle例如,你可以在這裏玩:http://sqlfiddle.com/#!3/4aac0/7
--First, get all the dates in the current year.
--This uses a Recursive CTE to generate a date
--for each week between a start date and an end date
--In SSRS you could create report parameters to replace
--these values.
WITH WeekDates AS
(
SELECT CAST('1/1/2012' AS DateTime) AS WeekDate
UNION ALL
SELECT DATEADD(WEEK,1,WeekDate) AS WeekDate
FROM WeekDates
WHERE DATEADD(WEEK,1,WeekDate) <= CAST('12/31/2012' AS DateTime)
),
--Next, add meta data to the weeks from above.
--Get the WeekYear and WeekNumber for each week.
--Note, you could skip this as a separate query
--and just included these in the next query,
--I've included it this way for clarity
Weeks AS
(
SELECT
WeekDate,
DATEPART(Year,WeekDate) AS WeekYear,
DATEPART(WEEK,WeekDate) AS WeekNumber
FROM WeekDates
),
--Cross join the weeks data from above with the
--Accounts table. This will make sure that we
--get a row for each account for each week.
--Be aware, this will be a large result set
--if there are a lot of weeks & accounts (weeks * account)
AccountWeeks AS
(
SELECT
*
FROM Weeks AS W
CROSS JOIN Accounts AS A
)
--Finally LEFT JOIN the AccountWeek data from above
--to the Visits table. This will ensure that we
--see each account/week, and we'll get nulls for
--the visit data for any accounts that were not visited
--in a given week.
SELECT
A.WeekYear,
A.WeekNumber,
A.AccountName,
A.AccountGroup,
IsNull(V.VisitAction,'not complete') AS VisitAction
FROM AccountWeeks AS A
LEFT JOIN Visits AS V
ON A.AccountName = V.AccountName
AND A.WeekNumber = DATEPART(WEEK,V.VisitDate)
--Set the maxrecursion number to a number
--larger than the number of weeks you will return
OPTION (MAXRECURSION 200);
我希望幫助。
你的問題有點不清楚。你想僅顯示數據中存在的日期,還是需要顯示日期,即使它們不在數據中? – BStateham
看到我的回答 [http:// stackoverflow。COM /問題/ 13831145/SQL查詢 - 複合內加入 - 和 - 外聯接] [1] [1]:http://stackoverflow.com/questions/13831145/sql-query -complex-inner-joins-and-outer-joins –
不幸的是我需要所有的帳戶名稱,無論他們在訪問表中。在訪問表中的那些賬戶中,我需要他們的數據。下面的代碼是我用來生成當前數據的帳戶和訪問詳細信息,但它不會顯示尚未訪問過的帳戶。不在那裏的賬戶。 –