左连接和匹配日期?
问题描述:
我试图将我的dimdate
表中的日期与我销售表中的日期进行匹配。使用left join
的原因是,我们可以看到2017-10-05
到2017-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
为空,这螺丝了报告,因为它显示了一个额外的行。
的另一个问题是,我不希望看到任何人的lastsale
是2017年10月10日,但只要我去掉and LastSale < '2017-10-10'
它成为一个inner join
,我没有看到任何2017-10 -05或2017-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-05
到2017-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
我以为我可以创造的所有日期的临时表和更新表一排,然后以某种方式使用工会,排除该行,但我知道必须有另一种方式。
感谢您的帮助。
答
对于从哪里参加一个像下面
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
请提供您的dimdate表的结构和简单的数据 –