基于两个计算列的计算列

编程入门 行业动态 更新时间:2024-10-27 02:25:07
本文介绍了基于两个计算列的计算列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试进行一个相当复杂的SELECT计算,我将对此进行概括:

I'm trying to do a rather complicated SELECT computation that I will generalize:

  • 主要查询是对表的通配符选择
  • 一个子查询根据条件对所有项目执行COUNT()(这很好)
  • 另一个子查询根据另一个条件在列中执行数字的SUM().这也可以正常工作,除非没有记录满足条件时,它返回NULL.
  • Main query is a wildcard select for a table
  • One subquery does a COUNT() of all items based on a condition (this works fine)
  • Another subquery does a SUM() of numbers in a column based on another condition. This also works correctly, except when no records meet the conditions, it returns NULL.
  • 我最初想将两个子查询加起来,就像(subquery1)+(subquery2) AS total一样,除非subquery2为null,否则工作正常,在这种情况下,无论subquery1的结果如何,total都将为null.我的第二个想法是尝试创建第三列来计算两个子查询(即(subquery1) AS count1, (subquery2) AS count2, count1+count2 AS total),但我认为不可能计算两个计算出的列,即使就像同样的问题一样.

    I initially wanted to add up the two subqueries, something like (subquery1)+(subquery2) AS total which works fine unless subquery2 is null, in which case total becomes null, regardless of what the result of subquery1 is. My second thought was to try to create a third column that was to be a calculation of the two subqueries (ie, (subquery1) AS count1, (subquery2) AS count2, count1+count2 AS total) but I don't think it's possible to calculate two calculated columns, and even if it were, I feel like the same problem applies.

    除了获取两个子查询值并将它们加到我的程序中之外,有人对这个问题有一个优雅的解决方案吗?

    Does anyone have an elegant solution to this problem outside of just getting the two subquery values and totalling them in my program?

    谢谢!

    推荐答案

    这里发生了两个问题:

    • 您不能在同一SELECT列表的另一个表达式中使用一个列别名.

    • You can't use one column alias in another expression in the same SELECT list.

    但是,您可以在派生表子查询中建立别名,并在外部查询中使用它们.

    However, you can establish aliases in a derived table subquery and use them in an outer query.

    您不能使用NULL进行算术运算,因为 NULL不为零.

    You can't do arithmetic with NULL, because NULL is not zero.

    但是,您可以使用COALESCE()函数将NULL默认"为非NULL值.此函数返回其第一个非NULL参数.

    However, you can "default" NULL to a non-NULL value using the COALESCE() function. This function returns its first non-NULL argument.

    这是一个例子:

    SELECT *, count1+count2 AS total FROM (SELECT *, COALESCE((subquery1), 0) AS count1, COALESCE((subquery2), 0) AS count2 FROM ... ) t;

    (请记住,必须为派生表赋予表别名,在此示例中为"t")

    (remember that a derived table must be given a table alias, "t" in this example)

    更多推荐

    基于两个计算列的计算列

    本文发布于:2023-10-13 20:26:43,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1488990.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:两个

    发布评论

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

    >www.elefans.com

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