Flag=1/0 基于同一列的多个条件

Flag=1/0 based on multiple criteria on same column

我有一个正在创建的临时 table,我们会说第 1 列是 YearMonth,第 2 列是 user_id,第 3 列是类型。

YearMonth User_id   Type
200101    1         x
200101    2         y
200101    2         z
200102    1         x
200103    2         x
200103    2         p
200103    2         q
     

我想根据基于类型的标志来计算用户 ID。因此,我试图将标志设置为 1 和 0,但结果总是 0。

例如当类型包含 x 或 y 或 z 且类型包含 P 或 Q 时,按 YearMonth.

我正在尝试

SELECT count (distinct t1.user_id) as count,
          t1.YearMonth,
          case when t1.type in ('x','y','z')
          and 
          t1.type in ('p','q') then 1 else 0 end as flag
      FROM table t1
      group by 2,3;

我想知道为什么它没有给出如下输出:

count YearMonth Flag
0      200001    1
2      200001    0
1      200002    1
1      200002    0
        

我在这里错过了什么?谢谢

如果我没听错的话,你可以使用两个级别的聚合:

select yearmonth, flag, count(*) cnt
from (
    select yearmonth, id,
        case when max(case when t1.type in ('x', 'y', 'z') then 1 else 0 end) = 1
              and max(case when t1.type in ('p', 'q') then 1 else 0 end) = 1
            then 1 
            else 0 
        end as flag
    from mytable
    group by yearmonth, id
) t
group by yearmonth, flag

这首先使用条件聚合标记每个月的用户,然后按标记和月份进行聚合。

如果您还想为给定月份未出现的标志显示 0,那么您可以先使用 cross join 生成组合,然后使用 left join:

select y.yearmonth, f.flag, count(t.id) cnt
from (select distinct yearmonth from mytable) y
cross join (values (0), (1)) f(flag)
left join (
    select yearmonth, id,
        case when max(case when t1.type in ('x', 'y', 'z') then 1 else 0 end) = 1
              and max(case when t1.type in ('p', 'q') then 1 else 0 end) = 1
            then 1 
            else 0 
        end as flag
    from mytable
    group by yearmonth, id
) t on t.yearmonth = y.yearmonth and t.flag = f.flag
group by y.yearmonth, f.flag

认为 一个与 GMB 非常相似的想法,但是,像他一样,我没有得到预期的结果。然而,我们都可能假设预期结果是错误的:

SELECT COUNT(DISTINCT UserID) AS [Count],
       YearMonth,
       CASE WHEN COUNT(CASE WHEN [Type] IN ('x','y','z') THEN 1 END) > 0
             AND COUNT(CASE WHEN [Type] IN ('p','q') THEN 1 END) > 0 THEN 1 ELSE 0
       END AS Flag
FROM (VALUES(200101,1,'x'),
            (200101,2,'y'),
            (200101,2,'z'),
            (200102,1,'x'),
            (200103,2,'x'),
            (200103,2,'p'),
            (200103,2,'q')) V(YearMonth,UserID,[Type])
GROUP BY YearMonth;