Postingan lainnya
Mysql : multiple select count
Permisi agan agan, saya mau bertanya
Kalau misal saya punya tabel begini
+-------+--------+-------+
| JUDUL | RATING | BY |
+-------+--------+-------+
| Gelas | 5 | Asrul |
+-------+--------+-------+
| Gelas | 5 | Djoko |
+-------+--------+-------+
| Gelas | 3 | Anwar |
+-------+--------+-------+
| Gelas | 3 | Khoir |
+-------+--------+-------+
| Sirup | 5 | Anwar |
+-------+--------+-------+
| Sirup | 4 | Anwar |
+-------+--------+-------+
| Sirup | 4 | Djoko |
+-------+--------+-------+
Nah yang mau saya tanyain, kalau misal saya pengen hitung "Gelas rate 5 nya berapa, rate 4 nya berapa, dan seterusnya begitu juga dengan sirup". Itu gimana ya caranya kalau dengan COUNT() ?
Sehingga nanti hasilnya
+-------+--------+-------+-------+
| JUDUL | rate5 | rate4 | rate3 |
+-------+--------+-------+-------+
| Gelas | 2 | 0 | 2 |
+-------+--------+-------+-------+
| Sirup | 1 | 2 | 0 |
+-------+--------+-------+-------+
Terima kasih
3 Jawaban:
coba begini gan
<pre>
SELECT judul,
COUNT(IF(rating
=5 ,1 ,NULL)) 'rate_5',
COUNT(IF(rating
=4 ,1 ,NULL)) 'rate_4',
COUNT(IF(rating
=3 ,1 ,NULL)) 'rate_3',
COUNT(IF(rating
=2 ,1 ,NULL)) 'rate_2',
COUNT(IF(rating
=1 ,1 ,NULL)) 'rate_1'
FROM nama_tabel
GROUP BY judul
</pre>
<div>coba ganti pakai SUM <a href="https://user-images.githubusercontent.com/309413/87864053-5a40f680-c98d-11ea-83bb-00ad9d3ded89.png">MySQL - Pivot by SUM</a></div>