如何将分组的列显示为单行,以使计数值在视觉上清晰可见?我认为必须有一种简洁的方法,而不是联接多个表以显示单个行。
我的桌子(tb)看起来像这样
Name Subjects
David Geography
David Geography
Sherry History
Paul History
Paul Math
Ken Chemistry
我想这样显示表格
Name Geography History Math Chemistry Total
David 2 0 0 0 2
Sherry 0 2 0 0 2
Paul 0 1 1 0 2
Ken 0 0 0 1 1
我在做多个联接表
SELECT g.name, g.count, h.count, m.count, c.count,
g.count + h.count + m.count + c.count as Total
FROM
(SELECT name, count(*) as count
FROM tb
WHERE Subjects = "Geography"
GROUP BY Name) as g
JOIN
(SELECT name, count(*) as count
FROM tb
WHERE Subjects = "History"
GROUP BY Name) as h
ON g.name = h.name
JOIN
(SELECT name, count(*) as count
FROM tb
WHERE Subjects = "Math"
GROUP BY Name) as m
ON g.name = m.name
JOIN
(SELECT name, count(*) as count
FROM tb
WHERE Subjects = "Chemistry"
GROUP BY Name) as c
ON g.name = c.name