我有一个包含clients_status的表,并且我的查询如下:
SELECT ROUND((SUM(client_status='BAD DEBT')/COUNT(*))*100) AS BAD,
ROUND((SUM(client_status='ALERT')/COUNT(*))*100) AS ALERT,
ROUND((SUM(client_status='REMIND BAYAR')/COUNT(*))*100) AS REMIND,
ROUND((SUM(client_status='RUTIN BAYAR')/COUNT(*))*100) AS RUTIN,
ROUND((SUM(client_status='POTENSI KOREKSI')/COUNT(*))*100) AS POTENSI,
ROUND((SUM(client_status='TOP 10')/COUNT(*))*100) AS TOP FROM clients
我应该怎么做才能使输出像这样:
Data value
===============
Bad 29
Alert 29
Remind 14
Rutin 14
Potensi 0
Top 15
请帮助大家...谢谢
答案 0 :(得分:0)
按状态汇总分组,然后交叉联接子查询以获取总计数以计算百分比。对于重命名和自定义顺序,您可以使用CASE
s。
SELECT cs.s data,
cs.c / ca.c * 100 value
FROM (SELECT CASE client_status
WHEN 'BAD DEPT' THEN
1
WHEN 'ALERT' THEN
2
WHEN 'REMIND BAYAR' THEN
2
WHEN 'RUTIN BAYAR' THEN
4
WHEN 'POTENSI KOREKSI' THEN
5
WHEN 'TOP 10' THEN
6
END o,
CASE client_status
WHEN 'BAD DEPT' THEN
'Bad'
WHEN 'ALERT' THEN
'Alert'
WHEN 'REMIND BAYAR' THEN
'Remind'
WHEN 'RUTIN BAYAR' THEN
'Rutin'
WHEN 'POTENSI KOREKSI' THEN
'Potensi'
WHEN 'TOP 10' THEN
'Top'
END s,
count(*) c
FROM clients
GROUP BY client_status) cs
CROSS JOIN (SELECT count(*) c
FROM clients) ca
ORDER BY cs.o;