I have a table similar to below in sql server 2005
date_column | field1 | field2
1 June 2012 | xyz | 53
1 June 2012 | abc | 87
2 June 2012 | xyz | 81
3 June 2012 | xyz | 54
3 June 2012 | abc | 53
3 June 2012 | abc | 54
4 June 2012 | mmn | 53
4 June 2012 | xyz | 54
4 June 2012 | mmn | 54
4 June 2012 | mmn | 55
3 June 2012 | abc | 55
3 June 2012 | adf | 86
3 June 2012 | asd | 33
I want to find all field1 values which has corresponding field2 values ’53’, ’54’ and ’55’. within the same date so output should be as below :
date_column | field1 | field2
3 June 2012 | abc | 53
3 June 2012 | abc | 54
3 June 2012 | abc | 55
4 June 2012 | mmn | 53
4 June 2012 | mmn | 54
4 June 2012 | mmn | 55
I tried the below sql code with inner join but it doesn’t work
select date_column, field1, field2 from table1
inner join (select date_column, field1, field2 from table1 where field2
in ('54', '55')) as table2
on table1.date_column = table2.date_column and
table1.field1 = table2.field1
where field1 in ('53', '54', '55')
group by date_column, field1, field2
order by date_column, field1, field2
I believe this should work? You might be overcomplicating this or I am misunderstanding the problem
Here is the SQLFiddle
You say you only need to find field1, so this should work, but if you need all columns, then you can do this:
Here is the SQLFiddle
OR, just add a WHERE if you only want the all columns for those in the 53-55:
Another Fiddle