我試過搜索,但我不完全確定如何提前道歉,如果這已在其他地方得到解答。SQL選擇日期範圍內的每個日期的所有內容,每個日期有多個值
我正在嘗試選擇日期範圍(包括那個日期沒有值的地方)的多個值之間的所有內容。我沒有真正解釋過,但下面是我之後輸出的一個例子。
Date Campaign Channel Transaction
01/01/2015 a Online Sale
01/01/2015 b Online Sale
01/01/2015 c Online Sale
01/01/2015 a Online Cancellation
01/01/2015 b Online Cancellation
01/01/2015 c Online Cancellation
01/01/2015 a Offline Sale
01/01/2015 b Offline Sale
01/01/2015 c Offline Sale
01/01/2015 a Offline Cancellation
01/01/2015 b Offline Cancellation
01/01/2015 c Offline Cancellation
02/01/2015 a Online Sale
02/01/2015 b Online Sale
02/01/2015 c Online Sale
02/01/2015 a Online Cancellation
02/01/2015 b Online Cancellation
02/01/2015 c Online Cancellation
02/01/2015 a Offline Sale
02/01/2015 b Offline Sale
02/01/2015 c Offline Sale
02/01/2015 a Offline Cancellation
02/01/2015 b Offline Cancellation
02/01/2015 c Offline Cancellation
我能夠選擇日期範圍之間,每天卻無法工作,如何選擇每天用即使沒有返回結果每個結果。
編輯 - 添加了解決方案,我發現
OK,所以我有這似乎是爲我工作的解決方案。可能有這樣做的更好的方式和任何建議表示讚賞,但這裏是我現在做
Declare @CC TABLE (Campaign varchar(50))
DECLARE @Channel Table (Channel Varchar(255))
DECLARE @TYPE TABLE (Transaction_Type varchar(255))
Insert Into @CC (Campaign) Values ('1')
Insert Into @CC (Campaign) Values ('2')
Insert Into @Channel (Channel) Values ('Online')
Insert Into @Channel (Channel) Values ('Inbound')
Insert Into @TYPE (Transaction_Type) Values ('Sale')
Insert Into @TYPE (Transaction_Type) Values ('Cancellation')
DECLARE
@StartDate DATE = Dateadd(YY,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)),
@EndDate DATE = Getdate()
SELECT
DATEADD(DAY, nbr - 1, @StartDate) as Dates,
Campaign,
Channel,
Transaction_Type
FROM (SELECT ROW_NUMBER() OVER (ORDER BY c.object_id) AS Nbr
FROM sys.columns c) nbrs,
@CC, @Channel, @TYPE WHERE nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)
Order by Dates asc, Campaign asc, Channel asc, Transaction_Type asc
我目前已經使用了下面的代碼創建一個靜態表。這將是需要再次使用的東西,所以認爲具有靜態表是有意義的。 'CREATE TABLE _Dates( d DATE, PRIMARY KEY(d) ) DECLARE @dIncr DATE = '2000-01-01' DECLARE @dEnd DATE = '2100年1月1日' WHILE(@dIncr < @dEnd) BEGIN INSERT INTO _Dates(d)VALUES(@dIncr) SELECT @dIncr = DATEADD(DAY,1,@dIncr) END' – 2014-12-09 12:26:07