sql - 使用另一列作为键添加值列

标签 sql postgresql psql

希望表格本身能说明问题。本质上,对于左侧的 Type 列,是否可以根据类型的出现顺序使用 Type 作为散列键/集来添加唯一的代码/值列:

Type | Code
-----------
ADA  |    1
ADA  |    1
BIM  |    2
BIM  |    2
CUR  |    3
BIM  |    2
DEQ  |    4
ADA  |    1
...  |  ...

我们不能简单地对转换进行硬编码,因为每次都有任意数量的 Type

最佳答案

你可以使用dense_rank():

select type, dense_rank() over (order by type) as code
from t;

但是,我建议您创建另一个表并使用它:

create table Types as (
    select row_number() over (order by type) as TypeId,
           type
    from t
    group by type;

然后,加入:

select t.type, tt.TypeId
from t join
     types tt
     on t.type = tt.type;

关于sql - 使用另一列作为键添加值列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42058401/

相关文章:

mysql - 使用SQL计算时间序列中的时间间隔

linux - 脚本自动化 postgres 设置

sql - 如何在其他字符中间使用 psql 变量?

mysql - Mariadb - 从用户 ID = 变量的所有消息列表中获取最新消息

php - 多答案枚举的 SQL DB 设计

mysql - 如何表扬附加值

sql - 获得从特定客户群购买的产品的百分比

postgresql - PreparedStatement 不起作用时如何在 JDBC 中转义 SQL 参数?

c++ - 带负载的 QT SQL 通知

postgresql - psql shell 中 username-# 和 username=# 的区别?