0

我有一张看起来像这样的桌子

编号 | 数字
---------------
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 查询是什么?

4

2 回答 2

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;
于 2013-03-21T13:51:34.833 回答
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,所以我假设您的意思是值。

于 2013-03-21T14:00:31.837 回答