我的数据库里有3个表( prodi
, mahasiswa
以及 status
),我正在尝试输出分组和计数的结果。
数据库创建sql
查询
SELECT
prodi.namaprodi,
(case when count(`status`.idsm)='1' then 1 else 0 end) as '1',
(case when count(`status`.idsm)='2' then 1 else 0 end) as '2',
(case when count(`status`.idsm)='3' then 1 else 0 end) as '3',
(case when count(`status`.idsm)='4' then 1 else 0 end) as '4',
(case when count(`status`.idsm)='5' then 1 else 0 end) as '5',
(case when count(`status`.idsm)='6' then 1 else 0 end) as '6',
(case when count(`status`.idsm)='7' then 1 else 0 end) as '7',
(case when count(`status`.idsm)='8' then 1 else 0 end) as '8'
FROM
`status`
INNER JOIN mahasiswa ON mahasiswa.idm = `status`.idm
INNER JOIN prodi ON prodi.idp = mahasiswa.idp
GROUP BY
prodi.idp, `status`.idm
实际结果
Hukum 0 1 0 0 0 0 0 0
Hukum 0 0 0 0 0 1 0 0
Hukum 0 1 0 0 0 0 0 0
Ekonomi 0 0 0 1 0 0 0 0
Ekonomi 0 0 0 1 0 0 0 0
期望结果
Hukum 0 2 0 0 0 1 0 0
Ekonomi 0 0 0 2 0 0 0 0
你知道如何让这个查询工作吗?
2条答案
按热度按时间8wigbo561#
在分组前将其放入子查询中
http://www.sqlfiddle.com/#!9/bf9dc9/10型
pcww981p2#
查询需要写成
我检查了查询,它给出了所需的结果。
当需要按多个列分组时,在子查询中创建一个组,在主查询中创建另一个组