How to find distinct columns in a nested subquery in SQL?

后端 未结 2 1185
时光说笑
时光说笑 2021-01-29 12:39

I need to find the distinct drinkers that ordered \'VODKA\' and \'WHISKY\'. I AM ONLY ALLOWED TO USE A NESTED QUERY. No other format is accepted.

I am quite new to sql

2条回答
  •  一整个雨季
    2021-01-29 13:29

    I think this will get you what you want. In the inner query you get two lines for a drinker if they drank both VODKA and WHISKY otherwise you get 1 or 0.

    The HAVING COUNT(*)=2 just returns those that had both. Then you just get the distinct DRINKER list.

    Since the DRINKER column appears in the ORDERS table, you do not need to reference the DRINKERS table at all.

    SELECT DISTINCT DRINKER
    FROM (SELECT DRINKER, COUNT(*)
          FROM (SELECT DISTINCT DRINKER, DRINK 
                       FROM ORDERS
                       WHERE DRINK IN("VODKA","WHISKY"))
          GROUP BY DRINKER
          HAVING COUNT(*)=2)
    

提交回复
热议问题