基于年龄分段分组统计各厂商消费总量的SQL语句编写求助
Solution to Your Age-Band Consumption Report Query
Let's get your query sorted to match the expected output you shared. Here's the breakdown of what needs fixing and the final working SQL:
Key Issues in Your Initial Query
- You were selecting the raw
ageinstead of the age band from your CASE statement - Your
GROUP BYclause only includedageband, but you need to group by both the age band and manufacturer to get totals per manufacturer within each age group - Using explicit
JOINsyntax instead of comma-separated tables makes the query easier to read and maintain
Corrected SQL Query
SELECT -- Use your CASE statement to define age bands, fixed the typo in the 55-64 range CASE WHEN age >=15 AND age <=24 THEN '15-24' WHEN age >=25 AND age <=34 THEN '25-34' WHEN age >=35 AND age <=44 THEN '35-44' WHEN age >=45 AND age <=54 THEN '45-54' WHEN age >=55 AND age <=64 THEN '55-64' -- Fixed the typo here (was 54-64 with upper limit 66) WHEN age >=65 THEN '65+' END AS `Age Category`, manu.manufacturer AS `Manufacturer`, SUM(consump.volume) AS `Total Volume Consumed` FROM indi INNER JOIN consump ON indi.id = consump.id INNER JOIN manu ON consump.code = manu.code -- Optional: Filter out any users without age data if needed WHERE indi.age IS NOT NULL GROUP BY `Age Category`, manu.manufacturer ORDER BY `Age Category`, manu.manufacturer;
Explanation
- Age Band Calculation: The CASE statement is embedded directly in the
SELECTclause to generate theAge Categorycolumn you need. I fixed a small typo where you had54-64for the 55-66 range (adjusted to55-64with upper limit 64 to keep the ranges consistent). - Table Joins: Using
INNER JOINexplicitly clarifies how the tables are linked, which is better practice than the old comma-separated syntax. - Grouping: We group by both
Age CategoryandManufacturerto ensure we get the total volume consumed for each manufacturer within every age segment. - Ordering: The
ORDER BYclause ensures the results are sorted neatly by age category and manufacturer, matching your expected output structure.
Notes
- If you want to include age categories that have no consumption data (showing 0 volume), you'd need to use
LEFT JOINinstead ofINNER JOINand handle NULL sums withCOALESCE(SUM(consump.volume), 0). - Make sure the
volumecolumn inconsumpis a numeric type (like INT or DECIMAL) soSUM()works correctly.
内容的提问来源于stack exchange,提问作者ManicWomanIRL
相关产品推荐
相关产品推荐

