合并有条件的许多表

时间:2019-03-29 07:14:11

标签: mysql sql mysqli

我应该在何处根据“角色”来区分用户?

这是我的小提琴 https://www.db-fiddle.com/f/rcsGy77aooBJFfXnvdi6K1/0

我的最后结果是这样的

enter image description here

我想基于“角色”添加更多列。也许会是这样

dinas_id | dinas_nama | total_user(Admin) | total_user(Kontraktor) | total_user(Pptk) | total_user(Bidang) | total_user(Konsultan) | total_user(Dll) | total_user(Owner) | total_bidang | total_kegiatan | total_paket 

1 个答案:

答案 0 :(得分:1)

也许这就是您要寻找的

SELECT dinas.dinas_id,
   dinas_nama,
   (select count(*) from sc_user where role='Admin' and dinas_id = dinas.dinas_id) as 'total_user(Admin)',
   (select count(*) from sc_user where role='Kontraktor' and dinas_id = dinas.dinas_id) as 'total_user(Kontraktor)',
   (select count(*) from sc_user where role='Pptk' and dinas_id = dinas.dinas_id) as 'total_user(Pptk)',
   (select count(*) from sc_user where role='Bidang' and dinas_id = dinas.dinas_id) as 'total_user(Bidang)',
   (select count(*) from sc_user where role='Konsultan' and dinas_id = dinas.dinas_id) as 'total_user(Konsultan)',
   (select count(*) from sc_user where role='Dll' and dinas_id = dinas.dinas_id) as 'total_user(Dll)',
   (select count(*) from sc_user where role='Owner' and dinas_id = dinas.dinas_id) as 'total_user(Owner)',
   COUNT(DISTINCT sc_bidang.bi_id) as total_bidang,
   COUNT(DISTINCT sc_kegiatan.ke_id) as total_kegiatan,
   COUNT(DISTINCT sc_kegiatan.ke_id, sc_paket.pa_id) as total_paket
FROM dinas
LEFT JOIN sc_user on dinas.dinas_id=sc_user.dinas_id
LEFT JOIN sc_bidang on dinas.dinas_id=sc_bidang.dinas_id
LEFT JOIN sc_kegiatan on dinas.dinas_id=sc_kegiatan.dinas_id
LEFT JOIN sc_paket on sc_paket.ke_id=sc_kegiatan.ke_id
GROUP by dinas.dinas_id