I'm looking for a sql statement for the following problem: Here is an excerpt from my table

'from_city' 'to_city'
New York    Boston
Chicago     New York
New York    Los Angeles
Dallas      San Francisco
Miami       New York
Dallas      Los Angeles

The expected result should look like this:

City              Count   Percentage
New York            4        33%
Los Angeles         2        17%
Dallas              2        17%
San Francisco       1         8%
Miami               1         8%
Chicago             1         8%
Boston              1         8%

So I need to union the two columns 'from_city' and 'to_city' which I was able to with:

(SELECT from_city AS City FROM table) UNION
(SELECT to_city AS City FROM table)

But now I don't know how to appy the count and percentage on the result set. Can you please help me out?

Thanks in advance!

有帮助吗?

解决方案

You may want to use subquery:

SELECT
  city,
  COUNT(1) AS c,
  CONCAT(100*COUNT(1)/sums.total, '%') AS p
FROM
  (SELECT  from_city AS city FROM t
  UNION ALL
  SELECT to_city FROM t) AS cities
  CROSS JOIN
  (SELECT 
     COUNT(from_city)
    +COUNT(to_city) AS total
  FROM t) AS sums
GROUP BY
  city
ORDER BY 
  c DESC

-note, that double count won't work in common case (thus used sum of counts by both columns) Check the demo.

Also you've not specified format of percentage - i.e. how many signs should be in it (because it may be non-integer) - so I've left it as it is

其他提示

SELECT City, COUNT(*) AS Count, ROUND(100*COUNT(*)/total) AS Percentage
FROM (SELECT from_city AS City
      FROM table
      UNION ALL
      SELECT to_city AS City
      FROM table
     ) AS u
CROSS JOIN (SELECT 2 * COUNT(*) AS total
            FROM table) AS t
GROUP BY City
ORDER BY Count DESC

DEMO

SELECT
    cities.City,
    COUNT(*) as `Count`,
    CONCAT((COUNT(*) / (SELECT COUNT(*)*2 FROM table)) * 100, '%') as Percentage
FROM (
    SELECT from_city AS City FROM table UNION ALL
    SELECT to_city AS City FROM table
) as cities
GROUP BY cities.City

I believe the following query will provide your desired results

SELECT 
  city, 
  count(*), 
  count(*)/(SELECT count(*)*2 FROM table)
FROM
  (SELECT from_city AS city FROM table
    union all
  SELECT to_city AS city FROM table) a
GROUP BY 
  city
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top