Row count in data range

  • Hello,

     

    May be somebody already addressed this question on the forum, but I could not find it.

     

    I have a table, for example:

     

    ID        Value

    --------------------

    1          3

    1          7

    1          24

    1          21

    2          10

    2          9

    2          15

    2          22

     

    How to count in one query the number of rows in different value ranges.

     

    So, result should look like this:

     

    ID        0_9      10_19  20_29

    -------------------------------------------

    1          2          0          1

    2          1          2          2

     

    Thank you.

  • How about:

    SELECT [ID]

            ,COUNT(CASE WHEN Value BETWEEN 0 AND 9 THEN 1 END) AS [0_9]

            ,COUNT(CASE WHEN Value BETWEEN 10 AND 19 THEN 1 END) AS [10_19]

            ,COUNT(CASE WHEN Value BETWEEN 20 AND 29 THEN 1 END) AS [20_29]

    FROM YourTable

    GROUP BY [ID]

  • Thanks a lot.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply