How to choose the sum of numbers less than 30 and the sum of numbers more than 30?

I am trying to write a SELECT statement to select the sum of a field, but I want to return a sum of numbers less than 30, as well as a sum of numbers greater than 30. I understand that I can do this with two selected compounds together, but I was hoping to find a “neat” way to do this.

+3
source share
3 answers

Something along these lines (correct the syntax for your environment):

SELECT
    sum(case when Field < 30 then Field else 0 end) as LessThan30,
    sum(case when Field > 30 then Field else 0 end) as MoreThan30
FROM
    DaTable
+19
source

, , thw, 30 30 , .

SELECT  SUM(CASE        WHEN col1 < 30 THEN COL1        ELSE 0 END
       )    SUM(CASE        WHEN col1 < 30 THEN COL1        ELSE 0 END
       ) FROM   DATABASE.SCHEMANAME.TABLE

,

+1

The requirement is a big vague one, but I will count SUM line by line and <> 30. This is different from the answer to the question.

SELECT
    SelectCol1, SelectCol2, SelectCol3, ..., SUM(AggregateCol)
FROM
    Table
GROUP BY
    SelectCol1, SelectCol2, SelectCol3, ...
HAVING
    SUM(AggregateCol) <> 30
+1
source

Source: https://habr.com/ru/post/1711793/


All Articles