取消透视两列并按同类群组分组

时间:2019-02-15 19:40:39

标签: sql sql-server

情况:

我有一个包含5列的表格:

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

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

+--------+--------+---------------+-------------+--------------+
| 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

1 个答案:

答案 0 :(得分: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;