英文:
Case sum in snowflake and name accordingly
问题
我已经将多个视图连接起来,以获取每个部门完成任务所需的时间的输出。输出如下所示:
| ID | PROCESS | DEPT| SECONDS
| -------- | -------------- |-------|
| S911 | BATCH |SALES |24268 |
| S911 | BATCH |MKTG |2992 |
| S911 | BATCH |HR |77 |
| S911 | BATCH |FIN |14995 |
| S911 | BATCH |DATA |739 |
| S911 | BATCH |ITA |8988 |
我希望输出如下所示:
| ID | PROCESS | DEPT_2 | SECONDS
| -------- | -------------- |-------|
| S911 | BATCH |EXEMPT |24345 |
| S911 | BATCH |NONEXEMPT|24722 |
| S911 | BATCH |OTHERS |2992 |
是否可以使用一个 case 语句来实现这个目标,其中 EXEMPT 是销售和人力资源的总和,NONEXEMPT 是财务、数据和产品的总和,如果还有其他部门,它们需要被汇总为 OTHERS。
英文:
I have joined multiple views to get the following output for time taken by each Department to complete a task. The output looks like this:
| ID | PROCESS | DEPT| SECONDS
| -------- | -------------- |-------|
| S911 | BATCH |SALES |24268 |
| S911 | BATCH |MKTG |2992 |
| S911 | BATCH |HR |77 |
| S911 | BATCH |FIN |14995 |
| S911 | BATCH |DATA |739 |
| S911 | BATCH |ITA |8988 |
I need the output to be this:
| ID | PROCESS | DEPT_2 | SECONDS
| -------- | -------------- |-------|
| S911 | BATCH |EXEMPT |24345 |
| S911 | BATCH |NONEXEMPT|24722 |
| S911 | BATCH |OTHERS |2992 |
Can this possibly done with a case statement where exempt is sum of sales and HR non exempt is sum of finance data and product and of there are any other departments they need to be summed up as others.
答案1
得分: 2
是的,你可以在聚合函数中使用一个case表达式。
我不使用Snowflake,但我相信你可以在group-by子句中使用列别名,具体如下所示,其中t
是你现有查询的派生表或公共表达式:
select Id, Process,
case
when dept in ('SALES', 'HR') then 'EXEMPT'
when dept in ('FIN', 'DATA', 'ITA') then 'NONEXEMPT'
else 'OTHERS'
end Dept_2,
Sum(Seconds) Seconds
from t
group by Id, Process, Dept_2
order by Dept_2;
英文:
Yes you can use a case expression in combination with an aggregation.
I don't use Snowflake but I believe you can use a column alias in a group-by clause, which would look as follows, where t
is a derived table or common table expression for your existing query:
select Id, Process,
case
when dept in ('SALES', 'HR') then 'EXEMPT'
when dept in ('FIN', 'DATA', 'ITA') then 'NONEXEMPT'
else 'OTHERS'
end Dept_2,
Sum(Seconds) Seconds
from t
group by Id, Process, Dept_2
order by Dept_2;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论