Search code examples
sqlsql-order-byunionrow-number

SQL ordering cities ascending and persons descending


I have been stuck in complicated problem. I do not know the version of this SQL, it is school edition. But it is not relevant info now anyway.

I want order cities ascending and numbers descending. With descending numbers I mean when there is same city couple times it orders then biggest number first.

I also need row numbers, I have tried SELECT ROW_NUMBER() OVER(ORDER BY COUNT(FIRST_NAME)) row with no succes.

I have two tables called CUSTOMERS and EMPLOYEES. Both of them having FIRST_NAME, LAST_NAME, CITY.

Now I have this kind of code:

SELECT 
CITY, COUNT(FIRST_NAME),
CASE WHEN COUNT(FIRST_NAME) >= 0 THEN 'CUSTOMERS'
END
FROM CUSTOMERS
GROUP BY CITY

UNION

SELECT 
CITY, COUNT(FIRST_NAME),
CASE WHEN COUNT(FIRST_NAME) >= 0 THEN 'EMPLOYEES'
END
FROM EMPLOYEES
GROUP BY CITY

This SQL code gives me list like this:

CITY
NEW YORK    2   CUSTOMERS
MIAMI       1   CUSTOMERS
MIAMI       4   EMPLOYEES
LOS ANGELES 1   CUSTOMERS
CHIGACO     1   CUSTOMERS
HOUSTON     1   CUSTOMERS
DALLAS      2   CUSTOMERS
SAN JOSE    2   CUSTOMERS
SEATTLE     2   CUSTOMERS
SEATTLE     5   EMPLOYEES
BOSTON      1   CUSTOMERS
BOSTON      3   EMPLOYEES

I want it look like this:

ROW  CITY
1    NEW YORK    2  CUSTOMERS
2    MIAMI       4  EMPLOYEES
3    MIAMI       1  CUSTOMERS
4    LOS ANGELES 1  CUSTOMERS
5    CHIGACO     1  CUSTOMERS
6    HOUSTON     1  CUSTOMERS
7    DALLAS      2  CUSTOMERS
8    SAN JOSE    2  CUSTOMERS
9    SEATTLE     5  EMPLOYEES
10   SEATTLE     2  CUSTOMERS
11   BOSTON      3  EMPLOYEES
12   BOSTON      1  CUSTOMERS

Solution

  • You can use window functions in the ORDER BY:

    SELECT c.*
    FROM ((SELECT CITY, COUNT(*) as cnt, 'CUSTOMERS' as WHICH
           FROM CUSTOMERS
           GROUP BY CITY
          ) UNION ALL
          (SELECT CITY, COUNT(*), 'EMPLOYEES'
           FROM EMPLOYEES
           GROUP BY CITY
          )
         ) c
    ORDER BY MAX(cnt) OVER (PARTITION BY city) DESC,
             city,
             cnt DESC;