我有一个看起来像这样的表格
id | number --------------- 1 56721 2 56722 3 43981 4 43982 5 43983 6 43984
My MySQL query looks like this:
SELECT CASE substr(number,1,2) WHEN '56' then 'class1' WHEN '43' then 'class2' else 'other' END as class,
CASE substr(number,3,2) WHEN '72' then 'subclass1', WHEN '98' then 'subclass2' ELSE 'other' END as subclass, count(id) as ct
FROM table GROUP BY class, subclass HAVING class!='other' AND subclass!='other'
ORDER BY class ASC, subclass DESC;
对应的 PostgreSQL 查询是什么?
最佳答案
为了使其更清晰,请将其包装在子查询上:
SELECT class, subclass
FROM
(
SELECT CASE substr(number,1,2) WHEN '56' then 'class1' WHEN '43' then 'class2' else 'other' END as class,
CASE substr(number,3,2) WHEN '72' then 'subclass1', WHEN '98' then 'subclass2' ELSE 'other' END as subclass
FROM table
) x
GROUP BY class, subclass
HAVING class != 'other' AND subclass != other
ORDER BY class ASC, subclass DESC;
关于MySQL 到 PostgreSQL 查询别名 GROUP BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15549376/