Best unofficial Apache Server developers community
Username
Forgot password?
Sign in with Twitter account
Sign in with Facebook account

SQL - Min Function...

0

34 views

My question is Write an SQL query that will determine which is the least expensive venue that will accommodate 120 people.

The Code i wrote

select v.venuename, min(v.costperday)
from venues v 
where v.venuecapacity = 120
Group By v.venuename; 

I am still getting both the answers and not the Least one.

But if i remove V.venueName from the select function.....i get the correct answer!

Why is that so ?

Your help would be highly appreciated. Thanks

asked June 19, 2011 8:49 am CDT
posted via StackOverflow

5 Answers

1
 
SELECT *
FROM (
    SELECT venuename, 
           costperday,
           min(costperday) over () as min_cost,
    FROM venues
    WHERE venuecapacity = 120
) v
WHERE v.min_cost = v.costperday

Or using a subselect:

SELECT *
FROM venues
WHERE venuecapacity = 120
AND costperday = (SELECT min(v2.costperday) 
                  FROM venues v2
                  WHERE v2.venuecapacity = 120)

You might want to use venuecapacity >= 120 in case there are venues that accomodate more than 120 people but are still cheaper than others that only allow exactly 120 people

answered June 19, 2011 9:27 am CDT
0
 
select v.venuename, min(v.costperday)
from 
(
  select venuename, costperday
  from venues
  where v.venuecapacity = 120) v

answered June 19, 2011 9:27 am CDT
0
 

That is because you select the lowest cost per day per venue if you include the name. In fact, the whole grouping is useless in this table as long as venuename is unique.

To get the venue with the lowest price use something like this:

select venuename, costperday
from
  venues v
where
  v.venuecapacity = 120 and
  v.costperday = (select min(costperday) from venue vs where va.venuecapacity = 120)

answered June 19, 2011 9:27 am CDT
0
 

I think this might be what you want:

SELECT venuename
  FROM (SELECT venuename, costperday, MIN(costperday) OVER () mincost
          FROM venues
         WHERE venuecapacity >= 120) q
 WHERE q.costperday = v.mincost;

Use >= 120, because you might not have any venues that have exactly 120 capacity, and you want all venues that can handle at least 120. Your requirements only state that the venue be able to accommodate 120 people, not that it handle exactly 120 people.

answered June 19, 2011 9:27 am CDT
-1
Best answer
 

You include the same field in the select list, thus the min will be computed for each of them not overall items

answered June 19, 2011 9:27 am CDT

Your answer

Join with account you already have


Sign in with Twitter account
Sign in with Facebook account
Sign in with Google Friend Connect

Preview
Similar questions
PHP function getHeader()
February 16, 2011
Ereg function in php
March 25, 2011
MD5 function in SQLite
February 22, 2011