开发者

A simple sql query question

开发者 https://www.devze.com 2023-01-16 18:11 出处:网络
suppose I have a table like this: table1: namefavorite_music acountry brock ajazz b开发者_StackOverflow社区jazz

suppose I have a table like this:

table1:

name     favorite_music
 a         country
 b         rock
 a         jazz
 b    开发者_StackOverflow社区     jazz

How can I do this query: find the names whose favorite_music style has both "country" and "jazz". For the example above, it should be only "a".


This should get them:

select name
from table1
where favorite_music = 'country'
intersect
select name
from table1
where favorite_music = 'jazz'

EDIT: The question is not very clear. The query above will return every name thas has both jazz and country as favorite music styles (in your example table, name='a')

EDIT 2: Just for fun, one example that should do it with one single scan, using a subquery:

select name from (
    select 
    name, 
    count(case when favorite_music = 'country' then 1 end) as likes_country,
    count(case when favorite_music = 'jazz' then 1 end) as likes_jazz,
    from table1
    where favorite_music in ('country', 'jazz')
    group by name
) where likes_country > 0 and likes_jazz > 0


SELECT t1.name  
FROM table1 as t1  
INNER JOIN table1 AS t2 ON t1.name = t2.name 
WHERE t1.favorite_music = 'jazz' AND t2.favorite_music = 'country'  


This will return all names that have at least country and jazz as favorite music:

select name from table1 where
  favorite_music in ('country', 'jazz')
group by name having count(name) = 2

This will return all names that have exactly (not more) country and jazz as favorite music:

select name from table1 t1 where
not exists (
  select * from table1 t2 where
    t1.name = t2.name and
    t2.favorite_music not in ('country', 'jazz')
)
group by name having count(name) = 2

The double negative can be tricky. You can read it like this: select all people who don't like music that isn't country or jazz. That means that they only like music that's country or jazz. The group by and having count = 2 just takes care that what they like is country and jazz.


Try this-->

select x.name from table1 x, table1 y
where
x.name = y.name and
x.favorite_music = 'country' and 
y.favorite_music = 'jazz'


pl/sql query

select name from table1 where favorite_music='country' or favorite_music= 'jazz' group by name having COUNT(name) > 1

OR

select name from (select name,favorite_music from table1 where favorite_music ='country' or favorite_music = 'jazz' group by name,favorite_music) group by name having COUNT(*) > 1

0

精彩评论

暂无评论...
验证码 换一张
取 消