我有一张看起来像这样的表
id | number --------------- 1 56721 2 56722 3 43981 4 43982 5 43983 6 43984
我的MySQL查询如下所示:
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查询是什么?
答案 0 :(得分:2)
为了使它更清晰,将其包装在子查询上:
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;
答案 1 :(得分:0)
如果number
实际存储为数字(这对我来说很有意义),那么您需要处理类型转换。 MySQL支持substr()
数值,但不支持Postgres:
SELECT class, subclass, count(*)
FROM (SELECT (CASE substr(numstr,1,2) WHEN '56' then 'class1'
WHEN '43' then 'class2'
else 'other'
END) as class,
(CASE substr(numstr,3,2) WHEN '72' then 'subclass1'
WHEN '98' then 'subclass2'
ELSE 'other'
END) as subclass
FROM (select t.*, cast(number as varchar(255)) as numstr
from table t
) t
) t
WHERE class <> 'other' AND subclass <> 'other'
GROUP BY class, subclass
ORDER BY class ASC, subclass DESC;
我还将having
子句中的比较更改为subclass <> 'other'
。没有名为other
的列,因此我假设您的意思是值。