使用SUM和CASE函数获取一行总和

时间:2019-06-26 19:23:35

标签: sql oracle syntax

我想创建一个输出,将与每个适合特定范围的变量关联的所有整数加起来。因此,第一列是范围(0-99、100-199等),第二列是变量的总数,第三列是求和。

我已经创建了用于创建前两列的格式,出于理解目的,我的目标是与第二列和第三列重新创建相同的表。

Ttable包含一个项目列表,每个项目都分配了一个值。

SELECT Ttable.SUM AS TotalTime,
        COUNT(*) AS Number

FROM 
    (SELECT 
    SUM(CASE WHEN count BETWEEN 0 AND 99 THEN [Value] ELSE 0 END) AS SUM FROM Ttable)
    (SELECT
    SUM(CASE WHEN count BETWEEN 100 AND 199 THEN [Value] ELSE 0 END) AS SUM FROM Ttable)
    (SELECT
    SUM(CASE WHEN count BETWEEN 200 AND 300 THEN [Value] ELSE 0 END) AS SUM FROM Ttable)
    Ttable
GROUP BY Ttable.SUM
ORDER BY Ttable.SUM;

代码返回第一和第二列

SELECT  Ttable.RANGE AS FileRange,
        COUNT(*) AS Number
FROM (
    SELECT 
    CASE
        WHEN count BETWEEN 0 AND 99 THEN '0 - 99'
        WHEN count BETWEEN 100 AND 199 THEN '100 - 199'
        WHEN count BETWEEN 200 AND 300 THEN '200 - 299'
        ELSE '300-399' END AS RANGE FROM table)
    Ttable
GROUP BY Ttable.RANGE
ORDER BY Ttable.RANGE;

我希望代码返回第二列和第三列

FileRange         Number        SumValues
 0 - 99            600            8000
100 - 199          400            5600
200 - 300          200            3000

但是我收到“ SQL命令未正确结束”

2 个答案:

答案 0 :(得分:0)

您似乎想要条件聚合:

SELECT COUNT(*) AS Number
       SUM(CASE WHEN count BETWEEN 0 AND 99 THEN [Value] ELSE 0 END) AS SUM_000_0999
       SUM(CASE WHEN count BETWEEN 100 AND 199 THEN [Value] ELSE 0 END) AS SUM_100_199,
       SUM(CASE WHEN count BETWEEN 200 AND 300 THEN [Value] ELSE 0 END) AS SUM_200_300
FROM table;

答案 1 :(得分:0)

只需将原始编号 count 保留在子查询SELECT中,然后将其汇总到外部查询中即可:

SELECT  Ttable."RANGE" AS FileRange,
        COUNT(*) AS "Number",
        SUM("count") As SumValues
FROM (SELECT 
            "count",
            CASE
               WHEN "count" BETWEEN 0 AND 99 THEN '0 - 99'
               WHEN "count" BETWEEN 100 AND 199 THEN '100 - 199'
               WHEN "count" BETWEEN 200 AND 300 THEN '200 - 299'
               ELSE '300-399' 
             END AS "RANGE"
      FROM table) Ttable
GROUP BY Ttable."RANGE"
ORDER BY Ttable."RANGE";

此外,请注意reserved words,例如 table count range ,它们在查询编译中可能会产生意想不到的结果。用双引号转义,或者最好使用不同的标识符或别名。