【问题标题】:Unpivot two columns and group by cohorts取消透视两列并按群组分组
【发布时间】:2019-07-09 23:49:16
【问题描述】:

情况:

我有一个有 5 列的表格:

  • 群组(NULL、1、2、3、4)
  • 状态 (0,1)
  • 电子邮件
  • Week_Number(该周登录的电子邮件)
  • Week_Number2(Week_Number 在 Week_Number2 期间登录的电子邮件)

我的主要查询产生了类似的结果:

+--------+--------+---------------+-------------+--------------+
| cohort | status |     email     | week_number | week_number2 |
+--------+--------+---------------+-------------+--------------+
| null   |      0 | aaa@email.com |           5 | 6            |
| 1      |      1 | bbb@email.com |           5 | 6            |
| 1      |      1 | ccc@email.com |           5 | 6            |
| 2      |      0 | ddd@email.com |           5 | NULL         |
| 3      |      1 | eee@email.com |           5 | 6            |
| 3      |      0 | fff@email.com |          5  | 6            |
| 4      |      0 | ggg@gmail.com |           5 | NULL         |
+--------+--------+---------------+-------------+--------------+

目标:

基本上,我想按群组、状态对结果进行分组,并在两周内 一列并添加总计数列。 我的输出应显示以下内容:

+--------+--------+-------------+-------------+
| cohort | status | week        | total_count |
+--------+--------+-------------+-------------+
| null   |      0 |           5 |           1 |
| null   |      0 |           6 |           1 |
| 1      |      1 |           5 |           2 |
| 1      |      1 |           6 |           2 |
| 2      |      0 |           5 |           1 |
| 3      |      0 |           5 |           1 |
| 3      |      0 |           6 |           1 |
| 3      |      1 |           5 |           1 |
| 3      |      1 |           6 |           1 |
| 4      |      0 |           5 |           1 |
+--------+--------+-------------+-------------+

我的第一个输出是:

SELECT 
     t3.Cohort
    ,t3.[Status]
    ,t1.Email
    ,t1.Week_Number
    ,t2.Week_Number2
FROM #table     AS t1     -- Gets first week info
LEFT JOIN #table2   AS t2 -- Gets second week info
    ON t1.Email=t2.Email
LEFT JOIN #table3   AS t3 -- Gets status and cohort
    ON t1.Email=t3.Email

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    我会使用apply 来取消透视数据。然后你似乎想要聚合:

    select t.Cohort, t3.[Status], v.week, count(*)
    from #table t cross apply
         (values (t.Week_Number), (t.Week_Number2)) v(week)
    where v.week is not null
    group by t.Cohort, t3.[Status], v.week;
    

    【讨论】:

    • 效果很好。为什么选择交叉应用而不是 unpivot?
    • @RogerSteinberg。 . . apply 是实现横向连接的通用运算符。横向连接非常强大并且有很多用途。 unpivot 是做一件事的神秘语法,而且——坦率地说——apply 在我看来甚至做得更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    相关资源
    最近更新 更多