I have a table of production with columns code
, name
, country
, production
I need to list countries that are exceeding the production of 1000 and also make a sum of production of all other countries and label it oth开发者_运维问答er. So the output will look like this
Country production
------- ----------
Japan 1380
England 1400
Other 2700
Is it possible to make this without union in one select?
Using a subquery:
SELECT CASE WHEN production >= 1000 THEN country ELSE 'Other' END country
, SUM(production) AS production
FROM(
SELECT country,
SUM(production) AS production
FROM production
GROUP BY country
) AS a
GROUP BY CASE WHEN production >= 1000 THEN country ELSE 'Other' END
Since you want to return all the data, but grouped differently you don't need to look at this task as a "Filtering" exercise, but only as a grouping/re-labeling exercise. To relabel everything with a production > 1000 you can use the case statement. All that is left to do is grouping. No need for any sub-queries.
SELECT country = CASE WHEN production >= 1000
THEN country
ELSE 'Other'
END
, production = SUM(production)
FROM production
GROUP BY CASE WHEN production >= 1000
THEN country
ELSE 'Other'
END
If the table can contain multiple records per country, the answer of @niktrs is correct.
精彩评论