简体   繁体   中英

how can oracle SQL return 6 count(columns) from one

I try to create a query, which counts different emission classes of cars, grouped by different country codes.

I can handle to do it with one emission_class , but fail to create it with all 7 of them. I'm not sure how to start a subquery for this, or should I try to UNION them?

thank you for your insight!

The code for a singel emission class count:

SELECT
  DISTINCT country_code,
  COUNT(emission_class) EURO0
FROM
  DB.CUSTOMER_VEHICLE
WHERE emission_class = 'E0'
GROUP BY country_code;

You can use SUM with CASE :

SELECT country_code
     , COUNT(emission_class) AS total
     , SUM(CASE WHEN emission_class = 'E0' THEN 1 ELSE 0 END) AS EURO0
     , SUM(CASE WHEN emission_class = 'E?' THEN 1 ELSE 0 END) AS EURO?
     , ...
FROM DB.CUSTOMER_VEHICLE
GROUP BY country_code;

This is what I think @Nightmaresux was trying to suggest:

SELECT country_code,
       emission_class,
       COUNT(*) cnt
FROM   DB.CUSTOMER_VEHICLE
GROUP BY country_code, emission_class;

It's an alternative to @notulysses's answer, but is slightly more flexible since it will work for any emission_class. However, it won't put each count into a new column, so it depends on what you're wanting the output to look like as to which proposed solution you go with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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