2017-10-10 70 views
1

我試圖將我的dimdate表中的日期與我銷售表中的日期進行匹配。使用left join的原因是,我們可以看到2017-10-052017-10-10之間的所有日期,並且SSRS矩陣顯示每個日期的列,即使它沒有任何數據。左連接和匹配日期?

這是一個例子查詢:

declare @table table 
(
    fname varchar(20), 
    Sales int, 
    SaleDate date, 
    LastSale date 
) 

insert into @table 
select 'John', 1, '2017/10/08', '2017/10/10' 
union 
select 'John', 3, '2017/10/09', '2017/10/10' 
union 
select 'John', 5, '2017/10/10', '2017/10/10' 
union 
select 'Mary', 1, '2017/10/06', '2017/10/08' 
union 
select 'Mary', 3, '2017/10/07', '2017/10/08' 
union 
select 'Mary', 5, '2017/10/08', '2017/10/08' 
union 
select 'Carl', 10, '2017/10/07', '2017/10/09' 
union 
select 'Carl', 13, '2017/10/08', '2017/10/09' 
union 
select 'Carl', 32, '2017/10/09', '2017/10/09' 


select dim.fulldatealternatekey as 'fulldate', fname, sales, t.SaleDate 
from dimdate dim left join @table t 
on dim.fulldatealternatekey = t.SaleDate 
where FullDateAlternateKey between '2017-10-05' and '2017-10-10' 
and LastSale < '2017-10-10' 

的問題是,沒有人有'10 -05-2017' 所以fname爲空,這螺絲了報告,因爲它顯示了一個額外的行。

的另一個問題是,我不希望看到任何人的lastsale2017年10月10日,但只要我去掉and LastSale < '2017-10-10'它成爲一個inner join,我沒有看到任何2017-10 -052017-10-10

理想的輸出應該是:

fulldate  fname sales SaleDate 
2017-10-05 Carl NULL  NULL 
2017-10-06 Carl NULL  NULL 
2017-10-07 Carl 10  2017-10-07 
2017-10-08 Carl 13  2017-10-08 
2017-10-09 Carl 32  2017-10-09 
2017-10-10 Carl NULL  NULL 
2017-10-05 Mary NULL  NULL 
2017-10-06 Mary 1  2017-10-06 
2017-10-07 Mary 3  2017-10-07 
2017-10-08 Mary 5  2017-10-08 
2017-10-09 Mary NULL  NULL 
2017-10-10 Mary NULL  NULL 

我只需要一個1 fname應包括所有fulldate期從2017-10-052017-10-10,因爲這是爲了讓SSRS顯示所有日期,所以這樣的事情也很大:

fulldate  fname sales SaleDate 
2017-10-05 Carl NULL NULL  -- It can be Carl or Mary, doesn't matter 
2017-10-07 Carl 10  2017-10-07 
2017-10-08 Carl 13  2017-10-08 
2017-10-09 Carl 32  2017-10-09 
2017-10-06 Mary 12  2017-10-06 
2017-10-07 Mary 32  2017-10-07 
2017-10-08 Mary 52  2017-10-08 
2017-10-10 Mary NULL NULL  -- It can be Carl or Mary, doesn't matter 

我以爲我可以創造的所有日期的臨時表和更新表一排,然後以某種方式使用工會,排除該行,但我知道必須有另一種方式。

感謝您的幫助。

+0

請提供您的dimdate表的結構和簡單的數據 –

回答

0

對於從哪裏參加一個像下面

select dim.fulldatealternatekey as 'fulldate', fname, sales, t.SaleDate 
from dimdate dim left join @table t 
on dim.fulldatealternatekey = t.SaleDate and LastSale < '2017-10-10' 
where FullDateAlternateKey between '2017-10-05' and '2017-10-10' 

標準最終輸出的lastDate問題變化情況,查詢應該是

select 
    dim.fulldatealternatekey as 'fulldate', 
    coalesce(fname, (SELECT TOP 1 fname from @table)) as fname, 
    sales, 
    t.SaleDate 
from dimdate dim left join @table t 
    on dim.fulldatealternatekey = t.SaleDate and LastSale < '2017-10-10' 
where FullDateAlternateKey between '2017-10-05' and '2017-10-10' 
order by dim.fulldatealternatekey asc