具有聚合函数的SQL GROUP BY CASE语句

编程入门 行业动态 更新时间:2024-10-16 18:40:45
本文介绍了具有聚合函数的SQL GROUP BY CASE语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

CASE 当col1> col2 THEN SUM(col3 * col4) ELSE 0 END as some_product

我想把它放在我的GROUP BY子句中,但这似乎会导致问题,因为列中有一个聚合函数。在这种情况下,有没有办法将GROUP BY列别名,如 some_product ,或者我需要把它放在子查询和组中?

解决方案

我的猜测是您并不真正想要 GROUP BY some_product。

答案:是否有一种方法可以为 GROUP BY 列别名例如在这种情况下的some_product,还是我需要把它放在子查询和组中? 是:您不能 GROUP BY 列别名。 $ b

b

select ... from(select ...,CASE WHEN col1> col2 THEN SUM(col3 * col4)ELSE 0 END as some_product 从... group by col1,col2 ...)T group by some_product ...

CTE:

with T as(select ...,CASE WHEN col1> col2 THEN SUM (col3 * col4)ELSE 0 END as some_product from ... group by col1,col2 ...) select ... from T group by some_product ...

I have a column that looks something like this:

CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product

And I would like to put it in my GROUP BY clause, but this seems to cause problems because there is an aggregate function in column. Is there a way to GROUP BY a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?

解决方案

My guess is that you don't really want to GROUP BY some_product.

The answer to: "Is there a way to GROUP BY a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?" is: You can not GROUP BY a column alias.

The SELECT clause, where column aliases are assigned, is not processed until after the GROUP BY clause. An inline view or common table expression (CTE) could be used to make the results available for grouping.

Inline view:

select ... from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product from ... group by col1, col2 ... ) T group by some_product ...

CTE:

with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product from ... group by col1, col2 ... ) select ... from T group by some_product ...

更多推荐

具有聚合函数的SQL GROUP BY CASE语句

本文发布于:2023-11-22 06:04:28,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   函数   GROUP   SQL   CASE

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!