【问题标题】:How to select from a table with additional where clause on a single column如何从单个列上带有附加 where 子句的表中进行选择
【发布时间】:2020-07-22 23:02:31
【问题描述】:

我在 Oracle 中编写 SQL 查询时遇到问题。这是我的示例表:

+----+-----------+-----------+--------+
| id | start     | end       | number |
+----+-----------+-----------+--------+
| 1  | 21-dec-19 | 03-jan-20 | 12     |
| 2  | 23-dec-19 | 05-jan-20 | 10     |
| 3  | 02-jan-20 | 15-jan-20 | 9      |
| 4  | 09-jan-20 | NULL      | 11     |
+----+-----------+-----------+--------+

这是我目前所拥有的:

SELECT
    SUM(number) AS total_number,
    SUM(number) AS total_ended_number -- (WHERE end IS NOT NULL)
FROM table
WHERE ... -- a lot of where clauses

以及想要的结果:

+--------------+--------------------+
| total_number | total_ended_number |
+--------------+--------------------+
| 42           | 31                 |
+--------------+--------------------+

我知道我可以在“total_ended_number”中进行单独的选择,但是初始选择已经有一堆 where 子句,它们也需要应用于内部选择。

我能够在 2 个单独的选择或 2 个嵌套选择中将其公式化,其中所有 where 子句都重复,但我的预期目标是不重复将在表上使用的 where 子句。

【问题讨论】:

    标签: sql oracle select sum


    【解决方案1】:

    您可以使用以下逻辑在 case 表达式上 sum

    SELECT
        SUM(number) AS total_number,
        SUM(CASE WHEN end IS NOT NULL THEN number END) AS total_ended_number
    FROM table
    WHERE ... -- a lot of where clauses
    

    【讨论】:

      【解决方案2】:
      SUM(case when "end" is not null then number else 0 end) AS total_ended_number
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        • 1970-01-01
        • 2019-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多