3

Im new to sql and playing around with some example databases I have found. I have a table called student as follows

id    name    expenditure      item
 1     dan      45              social
 1     dan      60              books
 2     sarah    32              food
 3     matt     64              food
 3     matt     71              social

I was trying to find students who spent money on both food and social but spent more money on social than food.

I tried:

Select name
from student
where  item = 'social' and item = 'food' 
1
  • 2
    Think about it: how can one column have the value 'social' and 'food' at the same time?
    – user330315
    Nov 19, 2012 at 15:47

2 Answers 2

7

No individual line of data has item = 'social' AND item = 'food'. As the WHERE clause applies to one row of data at a time, you can't do that.

What you need to do is group all the records together by student, and then check some characteristics of the data in that group.

SELECT
  id,
  name
FROM
  student
GROUP BY
  id,
  name
HAVING
      SUM(CASE WHEN item = 'social' THEN 1 ELSE 0 END) > 0
  AND SUM(CASE WHEN item = 'food'   THEN 1 ELSE 0 END) > 0

That gives all students who have some records for 'social' and some records for 'food'.

Then, you can add the following to get only those who spent more on 'social' than on 'food'.

AND SUM(CASE WHEN item = 'social' THEN expenditure ELSE 0 END)
    >
    SUM(CASE WHEN item = 'food'   THEN expenditure ELSE 0 END)
0
3

where  item = 'social' and item = 'food'  Doesn't work because a single row can never be both. When comparing two rows from the same table the easiest way is to do a self join

SELECT
   s1.Name
FROM student s1
     INNER JOIN student s2
      ON s1.id = s2.id
WHERE
    s1.item = 'social' and s2.item = 'food' 
    and 
    s1.expenditure  > s2.expenditure

Notes:

  1. If you have multiple rows for the same type of expenditures you'll want to use Dem's approach of summing the different types and then comparing

  2. If you want to include people who haven't spent any money on food you'll have to use a LEFT JOIN. You'll also to move the test for 'food' into the ON clause otherwise it will act like an inner join.

     LEFT JOIN student s2
      ON s1.id = s2.id
        and s2.item = 'food'   
    

SQL Fiddle Demo

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.