sql >> Database teknologi >  >> RDS >> Mysql

Procentdele i MySQL

Brug:

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

Hvis du vil have procentdelen med bestemte decimaler, skal du bruge:

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

Tjek, at dette giver det antal pr. virksomhed, du forventer:

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


  1. Det ultimative MySQL legacy database mareridt

  2. Udskrivning af en tabel vandret i stedet for lodret ved hjælp af PHP

  3. Dynamisk kolonnealias baseret på kolonneværdi

  4. Find MAX af SUM i MySQL