【发布时间】: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