Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 取消两列并按队列分组_Sql_Sql Server - Fatal编程技术网

Sql 取消两列并按队列分组

Sql 取消两列并按队列分组,sql,sql-server,Sql,Sql Server,情况: 我有一个有5列的表: 队列无效,1,2,3,4 状态0,1 电子邮件 周\在该周内登录的电子邮件数 第2周登录的第2周的电子邮件 我的主要查询结果如下: 目标: 基本上,我想分组的结果,队列,状态和有两个星期下 一列,并为总计数添加列。 我的输出应显示以下内容: +--------+--------+-------------+-------------+ | cohort | status | week | total_count | +--------+--------

情况:

我有一个有5列的表:

队列无效,1,2,3,4 状态0,1 电子邮件 周\在该周内登录的电子邮件数 第2周登录的第2周的电子邮件 我的主要查询结果如下:

目标:

基本上,我想分组的结果,队列,状态和有两个星期下 一列,并为总计数添加列。 我的输出应显示以下内容:

+--------+--------+-------------+-------------+
| 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
我将使用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;

那很好用。你为什么选择交叉申请而不是取消申请?@RogerSteinberg。apply是实现横向联接的通用运算符。横向连接功能非常强大,有很多用途。unpivot是一种晦涩难懂的语法,坦白说,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;