左连接和匹配日期?

时间:2017-10-10 21:05:10

标签: sql-server tsql reporting-services sql-server-2008-r2

我正在尝试将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为空,这会搞砸报告,因为它显示了额外的一行。

另一个问题是,我不希望看到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应该包含fulldate2017-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

我假设我可以创建一个包含所有日期的临时表,并用一行更新该表,然后以某种方式使用联合并排除该行,但我知道必须有另一种方式。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您的lastDate问题从WHERE更改为条件,如下所示

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'

为您的最终输出,查询应为

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