【问题标题】:Concat year and month but with a fixed size连接年份和月份,但大小固定
【发布时间】:2020-12-24 03:13:56
【问题描述】:

我有以下数据集:

CREATE TABLE my_table (
    the_debt_id varchar(6) NOT NULL, 
    the_debt_due date NOT NULL, 
    the_debt_paid timestamp NOT NULL
);

INSERT INTO my_table
VALUES ('LMUS01', '2020-08-02', '2020-05-18 11:07:01'), 
       ('LMUS01', '2020-07-02', '2020-05-18 11:07:01'), 
       ('LMUS01', '2020-06-02', '2020-05-18 11:07:01'), 
       ('LMUS01', '2020-05-02', '2020-04-28 02:28:41'),
       ('LMUS01', '2020-04-02', '2020-04-01 06:29:53'),
       ('LMUS01', '2020-03-02', '2020-03-02 07:30:59'),   
       ('LMUS01', '2020-02-02', '2020-01-31 06:58:18');

我只是想连接the_debt_due 的年份和月份,但是当我尝试这个时:

SELECT the_debt_id, 
cast(concat(extract('year' from the_debt_due),extract('month' from the_debt_due)) as integer) 
FROM my_table

它返回 1 月至 9 月月份的 5 位数字(如 5 月的 20205),其余时间的 6 位数字(如 12 月的 202012)。有可能得到六位数吗?这是预期的输出:

the_debt_id    concat     
LMUS01         202008
LMUS01         202007
LMUS01         202006
LMUS01         202005
LMUS01         202004
LMUS01         202003
LMUS01         202002

【问题讨论】:

  • 你需要一个字符串(用于显示)吗?还是一个 number (进行计算)? extract(),就像你拥有它一样,返回类型 double precisionconcat() 强制转换为 text,最后,你转换为 integer ...
  • 你好@ErwinBrandstetter,我需要一个整数来进行数学计算。我看到你已经回答了,谢谢!

标签: sql string postgresql datetime


【解决方案1】:

不需要填充逻辑。只需使用to_char()

select the_debt_id, to_char(the_debt_due, 'yyyymm') the_debt_due_char
from mytable

【讨论】:

    【解决方案2】:

    为了显示,请使用to_char(),就像提供的 GMB 一样。

    如果您需要integer,就像您的演员建议的那样,这比转换to_char() 的结果要快:

    SELECT (EXTRACT(year FROM the_debt_due) * 100 + EXTRACT(month FROM the_debt_due))::int;
    

    我在优化这个相关答案时测试了这两个:

    【讨论】:

    • 正是我需要的,一个整数!谢谢@Erwin Brandsetter!
    猜你喜欢
    • 2022-12-07
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多