如何使用SQL Server获取日期?

时间:2017-12-02 08:30:07

标签: sql sql-server tsql

我不知道怎么问这个问题。

我有两个表交易缺少

交易

id    Date
---------------
1     1-10-2016
2     2-10-2016
3     2-10-2016
6     5-10-2016
7     6-10-2016
8     7-10-2016
10    21-10-2016
16    23-10-2016
17    24-10-2016

缺少(这是缺少的表,它不在事务表中

ID
-----------
4
5
9
11
12
13
14
15

现在我想显示Missing.ID and Date,如下所示

id    Date
---------------
4     2-10-2016  //(this date is date of Transaction.id 3's date)
5     2-10-2016  //(this date is date of Transaction.id 3's date)

9     7-10-2016  //(this date is date of Transaction.id 8's date)

11    21-10-2016  //(this date is date of Transaction.id 10's date)
12    21-10-2016  //(this date is date of Transaction.id 10's date)
13    21-10-2016  //(this date is date of Transaction.id 10's date)
14    21-10-2016  //(this date is date of Transaction.id 10's date)
15    21-10-2016  //(this date is date of Transaction.id 10's date)

如果我想加入两个表,我可以加入哪个?此表之间没有链接

2 个答案:

答案 0 :(得分:3)

我建议使用apply运算符:

select id, ca.date
from missing
cross apply (
   select top(1) Transaction.date from Transaction
   where Transaction.id < missing.id
   order by Transaction.date DESC
   ) ca (date)

答案 1 :(得分:1)

您可以使用<table class="subtable4"> </table> <!--Table 1--> <table class="subtable4"> </table> <!--Table 2-->合并两个表数据(Transaction ... Missing)并使用合并的结果集将union all值替换为之前的null 1}}基于date的列值...并根据需要显示缺少id ids的联接操作,如下所示

date

结果:

;with cte as
(
    select id, [Date] from Transaction
    union all
    select id, null [Date] from Missing 
)
select m.id, t.[Date] from Missing m
join 
(
      select id, case when c.[Date] is null then 
      (select top 1 [Date] from cte WHERE id < c.id and [Date] is not null order by id desc)
      else c.[Date] end [Date]   
      from cte C 
) t on m.id = t.id