简体   繁体   English

SQL 查询组按邮政编码多个总和

[英]SQL Query group by Postcode multiple Sums

I have following data:我有以下数据:

ID ID Weight重量 Postcode邮政编码 Year
1 1 23 23 56222 56222 2022 2022
2 2 24 24 56332 56332 2022 2022
3 3 50 50 56442 56442 2022 2022
4 4 22 22 62331 62331 2022 2022
5 5 80 80 72130 72130 2022 2022

and i want to query it that i get the data like this: Grouped by Postcode and splitted in different weight ranges.我想查询我得到这样的数据:按邮政编码分组并分成不同的重量范围。 and then just Count of the amount of entrys.然后只是条目数量的计数。

Postcode/Weight邮编/重量 0-20 0-20 21-40 21-40 41-60 41-60 61-80 61-80 81-100 81-100
56 56 0 0 2 2 1 1 0 0 0 0
62 62 0 0 1 1 0 0 0 0 0 0
72 72 0 0 0 0 0 0 1 1 0 0

Is there any way to query this in SQL?有没有办法在 SQL 中查询这个?

Try this one.试试这个。

Query:询问:

SELECT 
    p.postcode, 
    COUNT(p20.id) as "0-20",
    COUNT(p40.id) as "21-40",
    COUNT(p60.id) as "41-60",
    COUNT(p80.id) as "61-80",
    COUNT(p100.id) as "81-100"
FROM packs p 
    LEFT JOIN packs p20 ON p20.postcode=p.postcode AND p20.weight < 20  
    LEFT JOIN packs p40 ON p40.postcode=p.postcode AND p40.weight >= 21 AND p40.weight <= 40 
    LEFT JOIN packs p60 ON p60.postcode=p.postcode AND p60.weight >= 41 AND p60.weight <= 60
    LEFT JOIN packs p80 ON p80.postcode=p.postcode AND p80.weight >= 61 AND p80.weight <= 80
    LEFT JOIN packs p100 ON p100.postcode=p.postcode AND p100.weight >= 81 AND p100.weight <= 100 
GROUP by postcode;

Result: Table结果:表格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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