【问题标题】:SQL Where In clause with multiple fields具有多个字段的 SQL Where In 子句
【发布时间】:2016-12-20 22:18:45
【问题描述】:

我有一张如下表。

id          date         value

1           2011-10-01   xx

1           2011-10-02   xx
...

1000000     2011-10-01   xx

然后我有 1000 个 ID,每个 ID 都与一个日期相关联。我想执行以下操作:

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

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

【问题讨论】:

  • 你的意思是:where (id, date) IN ( (1, date '2016-01-01'), (2, '2016-01-02'), ...) &lt;= 到底应该做什么?
  • 我想要的日期早于或等于我提供的日期。 SQL Server。

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


【解决方案1】:

您没有指定您的 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;

【讨论】:

  • 不那么标准。 MySQL 不支持 WITH。许多数据库(例如 Oracle、Teradata、MySQL...)不支持这种使用 VALUES。
  • @DuduMarkovitz:那是 100% ANSI 标准 SQL
  • 我们知道 ANSI 和“支持”之间存在巨大差异 :-)
  • 我的错。删除了我的答案。失焦 (00:44 :-))
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2011-05-26
    • 2018-07-19
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多