MySQL中的百分比

时间:2009-12-10 03:29:10

标签: mysql

使用此查询,

SELECT company, YEAR( date )  as year, COUNT( * ) as total
FROM table
WHERE company = "Medtronic"
OR company = "Private"
GROUP BY YEAR( date )

我得到这样一张桌子:

Company         year    total
Medtronic   1998    6
Private     1998    5
Medtronic   1999    5
Private     1999    1

如何计算每家公司每年贡献的百分比?

例如,Medtronic在1998年贡献的百分比是 6 /(6 + 5)= 54.5%

我一直试图通过MySQL查询来计算百分比。

谢谢你们。

2 个答案:

答案 0 :(得分:6)

使用:

SELECT x.company,
       x.year,
       x.annual_total
       x.annual_total / y.total AS percentage
  FROM (SELECT t.company, 
               YEAR(t.date) as year, 
               COUNT( * ) as annual_total
          FROM TABLE t
         WHERE t.company IN ('Medtronic', 'Private')
      GROUP BY YEAR( t.date ) ) x
  JOIN (SELECT t.company,
               COUNT(*) 'total'
          FROM TABLE t
         WHERE t.company IN ('Medtronic', 'Private')
      GROUP BY t.company) y ON y.company = x.company

如果您想要具有特定小数位的百分比,请使用:

CAST(x.annual_total / y.total AS DECIMAL(2,2)) AS percentage

检查这是否给出了您期望的每家公司的计数:

  SELECT t.company,
         COUNT(*) 'total'
    FROM TABLE t
   WHERE t.company IN ('Medtronic', 'Private')
GROUP BY t.company

答案 1 :(得分:0)

我的SQL查询:

SELECT x.company, x.year, x.annual_total, CAST( x.annual_total / y.total AS DECIMAL( 2, 2 ) ) AS percentage
FROM (

SELECT t.company, YEAR( t.date ) AS year, COUNT( * ) AS annual_total
FROM my_patents AS t
WHERE t.company = 'Private'
GROUP BY YEAR( t.date )
)x
JOIN (

SELECT t.company, COUNT( * ) AS total
FROM my_patents AS t
WHERE t.company = 'Medtronic'
OR t.company = 'Private'
GROUP BY t.company
)y ON y.company = x.company

我的结果:

Private  1998  5  0.04

当我运行此查询时:

SELECT t.company, YEAR( date ) , COUNT( * ) AS total
FROM my_patents AS t
WHERE t.company = 'Medtronic'
OR t.company = 'Private'
GROUP BY t.company, YEAR( date )

我得到了

Medtronic  1998  6
Private  1998  5