我使用sqlfiddle将表的文本表示转换为一系列 CREATE TABLE 和 INSERT INTO 语句:
CREATE TABLE CenterCodes
(`id` int, `name` varchar(3), `center1` varchar(9), `center2` varchar(7), `center3` varchar(7))
;
INSERT INTO CenterCodes
(`id`, `name`, `center1`, `center2`, `center3`)
VALUES
(1, 'abc', 'baroda', 'bhopal', 'chennai'),
(2, 'pqr', 'amhedabad', 'Surat', 'kolkata'),
(3, 'nml', 'bhopal', 'chennai', 'Surat'),
(4, 'fts', 'baroda', 'Surat', 'Baroda')
;
尝试以下查询。内部UNION
为每个字符串值生成多行,每组 3 列中的 2 列为 NULL。这些 NULL 然后被SUM()
外部查询中的聚合 s 消除,将行集折叠为每个字符串值一行。
SELECT
centername,
SUM(CASE WHEN centername = center1 THEN 1 ELSE 0 END) AS center1,
SUM(CASE WHEN centername = center2 THEN 1 ELSE 0 END) AS center2,
SUM(CASE WHEN centername = center3 THEN 1 ELSE 0 END) AS center3
FROM (
SELECT
center1 AS centername,
center1,
NULL AS center2,
NULL AS center3
FROM CenterCodes
UNION ALL
SELECT
center2 AS centername,
NULL AS center1,
center2,
NULL AS center3
FROM CenterCodes
UNION ALL
SELECT
center3 AS centername,
NULL AS center1,
NULL AS center2,
center3
FROM CenterCodes
) AS Centers
GROUP BY centername;