计算2个不同表中2列之间的百分比

时间:2014-02-05 00:44:58

标签: mysql sql

我想知道如何在两个单独的表中对两列进行划分。

我有两张桌子:

  • 比赛,显示所有车手的所有比赛

    Driver   | Race
    -----------------
    Driver 1 | Race 1
    Driver 1 | Race 2
    Driver 1 | Race 3
    Driver 2 | Race 1
    
  • Pposition ,显示所有车手的杆位

    Driver   | PP
    --------------
    Driver 1 | PP1
    Driver 1 | PP2
    Driver 2 | PP1
    

所以,我想知道如何获得驾驶员杆位的百分比(杆位/驾驶员比赛总数* 100)

我有这个查询,但它不起作用,结果是一个空表

SELECT R.Driver,
    P.Driver,
    (P.Driver/R.Driver)*100 AS M2 
FROM Races AS R 
INNER JOIN Pposition AS P ON R.Driver=P.Driver 
GROUP BY P.Driver HAVING R.Driver > 10 
ORDER BY M2 DESC
LIMIT 0,50

我想要的输出类似于

    Driver   | %
    -----------------
    Driver 2 | 100
    Driver 1 | 66.6

提前感谢所有

2 个答案:

答案 0 :(得分:0)

您可以使用子查询完成此操作。例如:

SELECT R.Driver, S.Cnt AS Races, P.Cnt AS Poles, (P.Cnt / S.Cnt) * 100 AS M2
FROM Races AS R
LEFT JOIN (SELECT Driver, COUNT(*) AS Cnt FROM Races) AS S ON S.Driver = R.Driver
LEFT JOIN (SELECT Driver, COUNT(*) AS Cnt FROM PPosition) AS P ON P.Driver = R.Driver
WHERE R.Driver > 10
ORDER BY M2 DESC

修改

这是一个子查询:

SELECT R.Driver, (P.Cnt * 100 / COUNT(*)) AS M2
FROM Races AS R
LEFT JOIN (SELECT Driver, COUNT(*) AS Cnt FROM PPosition GROUP BY Driver) AS P ON P.Driver = R.Driver
GROUP BY R.Driver, P.Cnt
ORDER BY M2 DESC

答案 1 :(得分:0)

但是,dub stylee的答案有一个必须修复的错误 -

Column 'PPosition.Driver' is invalid in the select list because 
it is not contained in either an aggregate function or the GROUP BY clause.

我就是这样做的 -

首先,将您的问题分成几部分。从每个表中获取分组数据 -

SELECT Driver, Count(Race) as [Races]
FROM Races
GROUP BY Driver

SELECT Driver, COUNT(PP) as [pposition]
FROM Pposition
GROUP BY Driver

然后,我们将其插入一个连接多个查询的查询 -

SELECT R.Driver, (P.pposition/R.Races)*100 AS M2 
FROM 
(
-- Put 1st query here
) AS R
INNER JOIN -- or left join
(
-- Put 2nd query here
) AS P
ON R.Driver = P.Driver 

然后,最终查询变为 -

SELECT R.Driver, (P.pposition/R.Races)*100.00 AS M2 
FROM 
(
SELECT Driver, Count(Race) as [Races]
FROM Races
GROUP BY Driver
) AS R
LEFT JOIN
(
SELECT Driver, COUNT(PP) as [pposition]
FROM Pposition
GROUP BY Driver
) AS P
ON R.Driver = P.Driver

仅使用您在问题中提供的数据,我得到一个输出 -

Driver  M2
Driver 1    100.00
Driver 2    100.00
Driver 3    NULL