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

前端 未结 4 478
攒了一身酷
攒了一身酷 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:38

    The following does what you want for all films:

    select r.*,
           (case when row_number() over (partition by filmname order by date) = 1
                 then 1 else 0
            end) as IsWatchedFirstAndGladiator
    from results r;
    

    For just Gladiator:

    select r.*,
           (case when filmname = 'Gladiator' and row_number() over (partition by filmname order by date) = 1
                 then 1 else 0
            end) as IsWatchedFirst
    from results r;
    
    0 讨论(0)
  • 2021-01-27 08:43

    So you're saying that:

    SELECT Cust_Nr, Date, FilmName, 
           CASE WHEN FilmName LIKE '%Gladiator%' THEN 1 ELSE 0 END as WatchedGladiator
    FROM YourTable
    WHERE YourColumn = @somevalue
    

    Doesn't work? Because according to the data you've given, it should.

    EDIT:

    Well based on Tim's comment, I would simply add this bit to the query.

       SELECT Cust_Nr, Date, FilmName, WatchedGladiator
       FROM
       (
          SELECT Cust_Nr, Date, FilmName, 
                 CASE WHEN FilmName LIKE '%Gladiator%' THEN 1 ELSE 0 END as WatchedGladiator
          FROM YourTable
          WHERE YourColumn = @somevalue
       ) as wg
       WHERE WatchedGladiator = 1
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-27 09:02

    Try grouping up to the cust/film level:

    select
    cust_nbr,
    case when film_name like '%Gladiator%' then 1 else 0 end
    from
    (
    select
        cust_nbr,
        film_name
        from
        <your table>
        group by
        cust_nbr,
        film_name
    ) t
    

    Or, as an alternative:

    select distinct cust_nbr
    from
    <your table>
    where 
    filmname = 'Gladiator'
    
    0 讨论(0)
提交回复
热议问题