Home > Database > Mysql Tutorial > How Can I Group Numerical Data into Ranges in SQL?

How Can I Group Numerical Data into Ranges in SQL?

Barbara Streisand
Release: 2025-01-17 21:21:11
Original
608 people have browsed it

How Can I Group Numerical Data into Ranges in SQL?

SQL Techniques for Binning Numerical Data

This guide demonstrates how to categorize numerical data into defined ranges within an SQL database. Imagine you have a table with a numerical column (e.g., "score"). The goal is to generate a summary showing the count of scores falling within each range.

Illustrative Example:

A summary table might look like this:

Score Range Frequency
0-9 11
10-19 14
20-29 3
... ...

Here's how to achieve this in SQL Server 2000 and beyond:

Method 1: CASE Expression within a Subquery

This method uses a CASE expression inside a subquery to assign range labels to each score, followed by an outer query to count occurrences within each range.

<code class="language-sql">SELECT t.range AS "Score Range", COUNT(*) AS "Frequency"
FROM (
  SELECT score,
         CASE  
           WHEN score BETWEEN 0 AND 9 THEN '0-9'
           WHEN score BETWEEN 10 AND 19 THEN '10-19'
           ELSE '20-99'  -- Handle scores outside defined ranges
         END AS range
  FROM scores
) t
GROUP BY t.range;</code>
Copy after login

Method 2: CASE Expression in the Main Query

Alternatively, the CASE expression can be directly embedded in the main query, simplifying the structure slightly.

<code class="language-sql">SELECT 
    CASE  
        WHEN score BETWEEN 0 AND 9 THEN '0-9'
        WHEN score BETWEEN 10 AND 19 THEN '10-19'
        ELSE '20-99'  -- Handle scores outside defined ranges
    END AS "Score Range",
    COUNT(*) AS "Frequency"
FROM scores
GROUP BY 
    CASE  
        WHEN score BETWEEN 0 AND 9 THEN '0-9'
        WHEN score BETWEEN 10 AND 19 THEN '10-19'
        ELSE '20-99'
    END;</code>
Copy after login

These methods efficiently group and summarize data into custom ranges, offering valuable insights into data distribution. Remember to adjust the CASE statements to match your specific score ranges. Consider adding error handling for values outside the defined ranges.

The above is the detailed content of How Can I Group Numerical Data into Ranges in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template