0

guys, I follow instruction from this link

I created table like this

CREATE TABLE cities
(
  city VARCHAR(80),
  country VARCHAR(80),
  population INT
);

INSERT INTO cities VALUES ('New York', 'United States', 8175133); 
INSERT INTO cities VALUES ('Los Angeles', 'United States', 3792621); 
INSERT INTO cities VALUES ('Chicago', 'United States', 2695598); 

INSERT INTO cities VALUES ('Paris', 'France', 2181000);
INSERT INTO cities VALUES ('Marseille', 'France', 808000);
INSERT INTO cities VALUES ('Lyon', 'France', 422000);

INSERT INTO cities VALUES ('London', 'United Kingdom',  7825300);
INSERT INTO cities VALUES ('Birmingham', 'United Kingdom', 1016800);
INSERT INTO cities VALUES ('Leeds', 'United Kingdom', 770800);     

when i run this query

SELECT city, country, population
  FROM
  (SELECT city, country, population, 
              @country_rank := IF(@current_country = country, @country_rank + 1, 1) AS country_rank,
              @current_country := country 
    FROM cities
    ORDER BY country, population DESC
   ) ranked
   WHERE country_rank <= 2;

it doesn't give me 2 largest cities for each country

Is there something I missed? thanks

2
  • Works for me: sqlfiddle.com/#!9/6a5a1/1 Commented Apr 3, 2015 at 3:36
  • it doesn't work for me, i checked my mysql version and it says 5.0 maybe i should upgrade to 5.6 thanks @Barmar Commented Apr 3, 2015 at 3:51

2 Answers 2

2

Add the below two line codes before your codes, and it will work.

SET @current_country:=NULL;
SET @country_rank:=0;


SELECT city, country, population
  FROM
  (SELECT city, country, population, 
             @country_rank := IF(@current_country = country, @country_rank + 1, 1) AS country_rank,
          @current_country := country 
  FROM cities
  ORDER BY country, population DESC
   ) ranked
   WHERE country_rank <= 2;
Sign up to request clarification or add additional context in comments.

Comments

0

Try adding another subquery to initialize the variables:

SELECT city, country, population
FROM
    (SELECT city, country, population, 
            @country_rank := IF(@current_country = country, @country_rank + 1, 1) AS country_rank,
            @current_country := country 
    FROM cities
    ORDER BY country, population DESC
) ranked
CROSS JOIN (SELECT @country_rank := 0, $current_country := '') vars  
WHERE country_rank <= 2;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.