简体   繁体   中英

Using SUM and CASE Functions to get a row of sums

I want to create a output adding up all the integers associated with each variable that fits with a certain range. So one column is the ranges (0-99,100-199,etc.), second column has the total number of variables, and the third column will be the summation.

I've created the format for creating the first two columns, and for understanding purposes my goal is just to recreate the same table with the second and third column.

The Ttable contains a list of items each assigned a value.

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;

Code returns columns one and two

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;

I expect the code to return columns two and three of

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

but I'm getting a "SQL command not properly ended"

You seem to want conditional aggregation:

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;

Simply keep the original number, count , in the subquery SELECT , then aggregate it in outer query:

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";

Also, be careful of reserved words such as table , count , and range which can have unintended results in query compilation. Escape by double quotes or better use different identifiers or aliases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM