1

I have a table as below.

id          date         value

1           2011-10-01   xx

1           2011-10-02   xx
...

1000000     2011-10-01   xx

Then I have 1000 ids each associates with a date. I would like to perform something as below:

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

What's the best way to achieve above query?

2
  • Do you mean: where (id, date) IN ( (1, date '2016-01-01'), (2, '2016-01-02'), ...) What exactly is that <= supposed to do? Commented Dec 20, 2016 at 22:21
  • I want the date before or equal to the date I provided. SQL Server. Commented Dec 20, 2016 at 22:23

2 Answers 2

5

You didn't specify your DBMS, so this is standard SQL.

You could do something like this:

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;

This assumes that you do not have duplicates in the list of dates.


Update - now that the DBMS has been disclosed.

For SQL Server you need to change that to:

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;
Sign up to request clarification or add additional context in comments.

4 Comments

Not so standard. MySQL does not support WITH. Many databases (e.g. Oracle,Teradata,MySQL...) do not support this use of VALUES.
@DuduMarkovitz: that is 100% ANSI standard SQL
As we know there is a HUGE difference between ANSI and 'supported' :-)
My bad. Deleted my answer. Out of focus (00:44 :-))
1

since this is info known ahead of time build a temp table of this info and then join to it

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.