gpt4 book ai didi

PostgreSql - 将 YEar 和 Month 添加到表中

转载 作者:行者123 更新时间:2023-11-29 12:38:23 24 4
gpt4 key购买 nike

我正在创建一个客户表,我希望其中一个属性是信用卡的到期日期。我希望格式为“月年”。我应该使用什么数据类型?我想使用日期,但格式是年/月/日。还有其他方法可以将格式限制为仅月和年吗?

最佳答案

您可以将日期限制为该月的第一天:

create table customer (
cc_expire date check (cc_expire = date_trunc('month', cc_expire))
);

现在失败了:

insert into customer (cc_expire) values ('2014-12-02');
ERROR: new row for relation "customer" violates check constraint "customer_cc_expire_check"
DETAIL: Failing row contains (2014-12-02).

这有效:

insert into customer (cc_expire) values ('2014-12-01');
INSERT 0 1

但是输入哪一天并不重要。你只会检查月份:

select
date_trunc('month', cc_expire) > current_date as valid
from customer;
valid
-------
t

分别提取年份和月份:

select extract(year from cc_expire) "year", extract(month from cc_expire) "month"
from customer
;
year | month
------+-------
2014 | 12

或串联:

select to_char(cc_expire, 'YYYYMM') "month"
from customer
;
month
--------
201412

关于PostgreSql - 将 YEar 和 Month 添加到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14915946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com