If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > Microsoft SQL Server > Select minimum from one table joining another...

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-20-11, 16:21
ManyTimes ManyTimes is offline
Registered User
 
Join Date: Jul 2010
Location: Norway
Posts: 16
Select minimum from one table joining another...

Hello!
Fairly easy problem, at least it should have been...


I have two tables

Table1
ID carID cost
1 1 25,-
2 2 30,-
3 1 40,-
4 1 26,-

Table2
ID carname carmodel
1 Ferrari 1990
2 Porsche 1991
3 Jaguar 1992

Here I have two simple tables, where the carID in table1 is the ID in the second table.
Now I want to return the minimum cost from table 1 for ALL cars at once.
Result wanted:
Ferrari 25,-
Porsche 30,-

Jaguar will not be in the result, since there is no price on it, it is so simple, yet... Jesus!

Tried:
Code:
SELECT  t1.price, t2.car FROM Price as t1
INNER JOIN Car as t2 ON t1.carID = t2.ID
WHERE
( t1.price = (SELECT min(t3.price) FROM Price as t3 ))
GROUP BY t1.price, t2.car;
Returns only the lowest cost of all cars:
Ferrari, 25
I am stuck!

Any tips and/or suggestions are more than welcome!

Edit: "Your" WYSIWYG editor for text bugs a bit if I put in colors? It uses :[COLOR="rgb(65, 105, 225)"], which fails... at least here, Flock browser. I put in "COLOR=RED" instead!
Reply With Quote
  #2 (permalink)  
Old 02-20-11, 16:50
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
Quote:
Originally Posted by ManyTimes View Post
Now I want to return the minimum cost from table 1 for ALL cars at once.
Code:
SELECT t2.carname
     , MIN(t1.cost) AS mincost
  FROM table2 AS t2
INNER
  JOIN table1 AS t1
    ON t1.carID = t2.id
GROUP
    BY t2.carname
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 02-20-11, 17:22
ManyTimes ManyTimes is offline
Registered User
 
Join Date: Jul 2010
Location: Norway
Posts: 16


Thanks, I managed to do it myself though. My bad was I grouped by several columns, which resulted in too many prices for a car, too many hours in a row in front of the computer does magical things to your thinking!
Reply With Quote
Reply

Tags
lowest, min, select, sql

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On