1

I have a table like this.

+  day +  person + amount +
+------+---------+--------+
+    1 +    John +      4 +
+------+---------+--------+
+    1 +     Sam +      6 +
+------+---------+--------+
+    2 +    John +      3 +
+------+---------+--------+
+    3 +    John +      3 +
+------+---------+--------+
+    3 +     Sam +      5 +
+------+---------+--------+
+    4 +    John +      3 +
+------+---------+--------+

How can I get a percentual of entries where the amount is greater than 3 (or other) grouped by people? I want my output to be: John 25%, Sam 100%. When the clause is "amount greater than 5", I would have: John 0%, Sam 50%. It would be nice to minimize the overload when table becomes big.

forpas
  • 160,666
  • 10
  • 38
  • 76
jackomelly
  • 523
  • 1
  • 8
  • 15

2 Answers2

2
SELECT person, 100 * SUM(amount > @criteria) / COUNT(*) needed_percent
FROM src_table
GROUP BY person

where @criteria is needed amount value (3, 5, etc.).

Akina
  • 39,301
  • 5
  • 14
  • 25
1

Use AVG() aggregate function with conditional aggregation:

SELECT person,
       100 * AVG(amount > ?) percent
FROM tablename
GROUP BY person;

See the demo.

forpas
  • 160,666
  • 10
  • 38
  • 76