MySQL 到 PostgreSQL 查询别名 GROUP BY

标签 mysql postgresql group-by sql-order-by alias

我有一个看起来像这样的表格

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/

相关文章:

php - MySQL 重复检查不起作用

sql - 更新表格单元格以仅具有唯一值

sql - 基于一列对数据进行分组

objective-c - PQgetResult 总是返回 NULL

pandas.hashtable.PyObjectHashTable.get_item 中的 Python pandas groupby 键错误

Python 提取一个新的数据框

php - mySQL 到 PHP 到 jQuery 返回浮点值作为字符串 (JSON)

PHP : How to pass get value in url

php - Laravel 5.1( Eloquent )在使用关系附加或分离时不起作用

mysql - SQL update 在update运行的过程中会影响它的子查询吗?