我正在寻找以下问题的sql语句: 这是我表格的摘录
'from_city' 'to_city'
New York Boston
Chicago New York
New York Los Angeles
Dallas San Francisco
Miami New York
Dallas Los Angeles
预期结果应如下所示:
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%
所以我需要将两个列'from_city'和'to_city'联合起来,我可以用它:
(SELECT from_city AS City FROM table) UNION
(SELECT to_city AS City FROM table)
但现在我不知道如何应用结果集的计数和百分比。 你能帮帮我吗?
提前致谢!
答案 0 :(得分:0)
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
答案 1 :(得分:0)
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
答案 2 :(得分:0)
我相信以下查询将提供您想要的结果
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
答案 3 :(得分:0)
您可能想要使用子查询:
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
- 注意,双重计数在常见情况下不起作用(因此使用两列的计数总和)检查demo。
此外,您还没有指定百分比格式 - 即应该包含多少个符号(因为它可能是非整数) - 所以我已将其保留原样