This answer通过以下查询解决了最初提出的问题(与将行数据转换为列数据有关):
SELECT
(SELECT count(*) FROM table1 WHERE type2 = 'T1' AND type1 = mTable1.type1) AS T1,
(SELECT count(*) FROM table1 WHERE type2 = 'T2' AND type1 = mTable1.type1) AS T2,
(SELECT count(*) FROM table1 WHERE type2 = 'T3' AND type1 = mTable1.type1) AS T3
FROM table1 mTable1 GROUP BY type1
通过测试代码,我可以看到表别名对于查询正常工作是必需的;下面的查询不起作用。
SELECT
(SELECT count(*) FROM table1 WHERE type2 = 'T1' AND type1 = table1.type1) AS T1,
(SELECT count(*) FROM table1 WHERE type2 = 'T2' AND type1 = table1.type1) AS T2,
(SELECT count(*) FROM table1 WHERE type2 = 'T3' AND type1 = table1.type1) AS T3
FROM table1 GROUP BY type1
不过,我不明白为什么需要别名。为什么第二个查询的含义不同于第一个查询?
答案 0 :(得分:3)
忘记表别名。简化代码!
SELECT type1,
SUM(CASE WHEN type2 = 'T1' THEN 1 ELSE 0 END) AS T1,
SUM(CASE WHEN type2 = 'T2' THEN 1 ELSE 0 END) AS T2,
SUM(CASE WHEN type2 = 'T3' THEN 1 ELSE 0 END) AS T3
FROM table1 t1
GROUP BY type1;
在您的代码版本中,需要使用表别名,以便可以将对table1
的内部引用与对同一表的外部引用相关联。在这两种情况下,表名都相同,因此需要使用表名以外的其他内容来引用列。