SQL Where子句有多个字段

时间:2016-12-20 22:18:45

标签: sql sql-server where-clause where-in sql-in

我有一张桌子如下。

id          date         value

1           2011-10-01   xx

1           2011-10-02   xx
...

1000000     2011-10-01   xx

然后我有1000个ID,每个人都有一个约会。我想执行以下操作:

SELECT id, date, value
FROM the table
WHERE (id, date) IN ((id1, <= date1), (id2, <= date2), (id1000, <= date1000))

实现上述查询的最佳方法是什么?

2 个答案:

答案 0 :(得分:5)

您没有指定DBMS,因此这是标准SQL。

你可以这样做:

with list_of_dates (id, dt) as (
  values 
     (1, date '2016-01-01'), 
     (2, date '2016-01-02'),
     (3, date '2016-01-03')  
)
select 
from the_table t
  join list_of_dates ld on t.id = ld.id and t.the_date <= ld.dt;

这假设您在日期列表中没有重复项。

更新 - 现在已经披露了DBMS。

对于SQL Server,您需要将其更改为:

with list_of_dates (id, dt) as (
  values 
     select 1, cast('20160101' as datetime) union all
     select 2, cast('20160102' as datetime) union all
     select 3, cast('20160103' as datetime)
)
select 
from the_table t
  join list_of_dates ld on t.id = ld.id and t.the_date <= ld.dt;

答案 1 :(得分:1)

因为这是提前知道的信息,所以建立一个这个信息的临时表,然后加入它

create table #test(id int, myDate date)
insert into #test(id,myDate) values
(1, '10/1/2016'),
(2, '10/2/2016'),
(3, '10/3/2016')

select a.id, a.date, a.value
from table as a
     inner join
     #test as b on a.id=b.id and a.date<=b.myDate
相关问题