+ -
当前位置:首页 → 问答吧 → 数据提取

数据提取

时间:2011-11-14

来源:互联网

如何按条件提某一天对应当的数据
例 A表有如下列
  j i d e 
2002 2010-01-01 00:0000 231 21
2002 2011-01-01 01:00:09 2543 98
2002 2011-10-01 01:10:09 32 22

B表
   
ji ei e e
2002 2011-01-02 12:00:32 22 121
2002 2011-10-02 01:10:59 33 444

我想要的结果是,如何提取在B表ei列条件下,提取A表d的数据...也就是提取ei日期前一天作为条件对应当的数据。
 
想要的结果是A表对应的数据

231
32

作者: jindeng   发布时间: 2011-11-14

没有看懂

作者: fredrickhu   发布时间: 2011-11-14

SQL code
select * from A
 where exists(select 1 from B where datediff(day,A.i,B.ei)=1)

作者: ssp2009   发布时间: 2011-11-14

楼主给的结果数据有问题
B表的2011-01-02日期前一天在A表中有两条,但你只列出一条

作者: pengxuan   发布时间: 2011-11-14

错了,2011-01-02日期前一天在A表中的d应该是2543 
SQL code

if object_id('A','U') is not null 
   drop table A
go
create table A
(
 j int,
 i datetime,
 d int,
 e int
)
go
insert into A
select 2002,'2010-01-01 00:00:00',231,21 union all
select 2002,'2011-01-01 01:00:09',2543,98 union all
select 2002,'2011-10-01 01:10:09',32,22
go
if object_id('B','U') is not null
   drop table B
go
create table B
(
 ji int,
 ei datetime,
 d int,
 e int
)
go
insert into B
select 2002,'2011-01-02 12:00:32',22,121 union all
select 2002,'2011-10-02',33,444
go
select A.d from A inner join B on convert(varchar(10),A.i,120)=convert(varchar(10),dateadd(dd,-1,B.ei),120)
/*
d
-----------
2543
32

(2 行受影响)
*/

作者: pengxuan   发布时间: 2011-11-14

SQL code
231--这条数据不对吧,

--> --> (Roy)生成測試數據
 
declare @A table([j] int,[i] datetime,[d] int,[e] int)
Insert @A
select '2002',N'2010-01-01 00:00:00',231,21 union all
select '2002',N'2011-01-01 01:00:09',2543,98 union all
select '2002',N'2011-10-01 01:10:09',32,22

--> --> (Roy)生成測試數據
 
declare @B table([ji] int,[ei] Datetime,[e] int,[e2] int)
Insert @B
select '2002','2011-01-02 12:00:32',22,121 union all
select '2002','2011-10-02 01:10:59',33,444
 
 Select a.* 
from @A as a
    inner join @B as b on convert(varchar(10),b.ei,120)=convert(varchar(10),a.i+1,120)
    
Select a.* 
from @A as a
    inner join @B as b on DATEDIFF(d,b.ei,a.i)=-1
/*
    j    i    d    e
2002    2011-01-01 01:00:09.000    2543    98
2002    2011-10-01 01:10:09.000    32    22
*/


作者: roy_88   发布时间: 2011-11-14