Using OVER() if customer has watch gladiator then 1 else 0 SQL SERVER

前端 未结 4 512
攒了一身酷
攒了一身酷 2021-01-27 08:27

I think I need some guidance as to what is wrong in my query. I am trying to do

Watched_Gladiator=CASE WHEN FilmName IN (CASE WHEN FilmName LIKE \'%Gladiator%\'         


        
4条回答
  •  灰色年华
    2021-01-27 08:50

    So you want to group by customer and add a column if this customer watched a specific film?

    You could do:

    SELECT Cust_Nr, MAX(Watched_Gladiator) 
    FROM( SELECT Cust_Nr, 
                Watched_Gladiator = CASE WHEN EXISTS
                (
                  SELECT 1 FROM CustomerFilm c2
                  WHERE c2.Cust_Nr = c1.Cust_Nr 
                  AND   c2.FilmName LIKE '%Gladiator%'
                ) THEN 1 ELSE 0 END
         FROM CustomerFilm c1 ) X
    GROUP BY Cust_Nr
    

    Demo

    But it would be easier if you used the customer-table instead of this table, then you don't need the group-by.

提交回复
热议问题