0
votes

I have an example table as such:

Year, Make, Model
1991 Honda Accord
1992 Honda Accord
1993 Honda Accord
1993 Ford Explorer

If I want to get all the Makes that are in production from 1992-1993, the returned rows should be "Honda", since Ford(in my example) only produced one car in 1993, but not one in 1992.

Any ideas on the query I can use?

EDIT:

Using the query from the answer below to use IN statements, does work, but when I do 25 IN statements, the time it takes is too long and it times out.

I tested it starting like 1990 1991, and then 1990 1991 1992, etc... when it gets around 2000 it takes too long and times out. I do have the choice of just doing two years(begin year, and end year) but I fear that wont be as accurate, as a manufacturer could have products a car in the beginning year parameter, and even the end year parameter, but have NOT produced a car somewhere in between, and even worse, when I start doing this with Models instead of makes, I definitely HAVE to check all years.

Table definition

CREATE TABLE Cars
( year INT,
  Make VARCHAR(20),
  Model VARCHAR(20)
 );

Table Data

INSERT INTO Cars
SELECT 1991, 'Alfo', 'Rom'
UNION
SELECT 1992, 'Alfo', 'Rom'
UNION
SELECT 1993, 'Alfa', 'Rom'
UNION
SELECT 1994, 'Alfa', 'Rom'
UNION
SELECT 1992, 'Honda', 'Accord'
UNION
SELECT 1993, 'Honda', 'Accord'
UNION
SELECT 1994, 'Honda', 'Del Sol'
UNION
SELECT 1993, 'Acura', 'Integra'
UNION
SELECT 1994, 'Acura', 'TL'
UNION
SELECT 1993, 'Ford', 'Explorer'
UNION
SELECT 1994, 'Honda', 'Accord';

SQL Fiddle

2

2 Answers

1
votes

I tested it starting like 1990 1991, and then 1990 1991 1992, etc... when it gets around 2000 it takes too long and times out. I do have the choice of just doing two years(begin year, and end year) but I fear that wont be as accurate, as a manufacturer could have products a car in the beginning year parameter, and even the end year parameter, but have NOT produced a car somewhere in between, and even worse, when I start doing this with Models instead of makes, I definitely HAVE to check all years.

You need to use HAVING and COUNT

SELECT  t.Make
FROM   
    (SELECT DISTINCT c.YEAR, c.Make
    FROM cars c) t 
WHERE t.YEAR IN (1992,1993,1994)  -- all the years
GROUP BY t.make
HAVING COUNT(*) = 3 --total number of years

SQL Fiddle Demo

1
votes

A couple of in operators will do the trick:

SELECT make
FROM   my_table
WHERE  make IN (SELECT make 
                FROM   my_table
                WHERE  year = 1992) AND
       make IN (SELECT make 
                FROM   my_table
                WHERE  year = 1993)