Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

mysql - Turn two lines result query in one

I have a table:

id | municipio_id |  ano | populacao
 1 |            0 | 2010 |      5000
 2 |            0 | 2011 |      5000

I create a query:

SELECT
case when ano = 2010 then populacao end a2010,
case when ano = 2011 then populacao end a2011
FROM populacao
where municipio_id = 0

The result is:

a2010 | a2011    
 5000 |  null
 null |  5000

I need like below:

a2010 | a2011    
 5000 |  5000

Any help?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want aggregation:

SELECT SUM(case when ano = 2010 then populacao end) as a2010,
       SUM(case when ano = 2011 then populacao end) as a2011
FROM populacao
WHERE municipio_id = 0;

If you want it for all municipios, then use GROUP BY:

SELECT municipio_id,
       SUM(case when ano = 2010 then populacao end) as a2010,
       SUM(case when ano = 2011 then populacao end) as a2011
FROM populacao
GROUP BY municipio_id;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...