Below is my table called fittest. I need to find which students based on student id (studid) have taken the pre and post test as designated in the prepost column. So based on the simple table below I would need to return studid 123456. How do I write the SELECT query for this?
SQL query: SELECT studid, prepost FROM `fittest` LIMIT 0, 30 ;
studid prepost
123456 pre
123456 post
1031460 pre
To select multiple values, you can use where clause with OR and IN operator.
Save this answer. Show activity on this post. select * will return values for all the columns in the table that have rows that match your predicate, while select column_name will only return the values in the column_name column for the rows that match your predicate. Save this answer.
Select the header or the first row of your list and press Shift + Ctrl + ↓(the drop down button), then the list has been selected except the first row.
Try
SELECT studid
FROM fittest
GROUP BY studid
HAVING COUNT(DISTINCT prepost) = 2
or if you want to ensure that only ids that have exactly one row with pre
and one row with post
then you can enforce it like this
SELECT studid
FROM fittest
GROUP BY studid
HAVING (MAX(prepost = 'pre' ) +
MAX(prepost = 'post')) = 2
AND COUNT(DISTINCT prepost) = 2
Output:
| STUDID | ---------- | 123456 |
Here is SQLFiddle demo for both queries
What about a JOIN:
select s1.studid, s1.prepost, s2.prepost
from fittest s1
inner join fittest s2
on s1.studid = s2.studid
where s1.prepost = 'pre'
and s2.prepost = 'post'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With