sql - 如何使用确切的年数间隔?
问题描述
我需要以这种方式格式化以获得年数、月数及其组合或“无保修”,具体取决于给定产品是否有保修。我尝试使用 case + extract 但它没有用
select p.product_name, sum(o.quantity) as total_quantity,
case when p.warranty_period = interval '0-0' year to month then 'No
warranty'
when p.warranty_period < interval '0-11' year to month then
extract(month from p.warranty_period) || ' months'
when p.warranty_period < interval '21-0' year to month then -- make it
for all years, not only 1
extract(year from p.warranty_period) || ' years'
when p.warranty_period > interval '0-0' year to month then
extract(year from p.warranty_period) || ' years and ' || extract(month
from p.warranty_period)
|| ' months'
end WARRANTY from PRODUCT_INFORMATION p
join order_items o on p.product_id = o.product_id
group by p.product_name, p.warranty_period;
我希望得到一个包含 4 个变量的列 WARRANTY:
没有保修
- 年
- 月
- 年月
解决方案
您可以使用以下内容:
-- Data preparation
create table product (warranty_period INTERVAL YEAR TO MONTH);
insert into product values(INTERVAL '2-0' YEAR TO MONTH)
insert into product values(INTERVAL '1-5' YEAR TO MONTH)
insert into product values(INTERVAL '0-7' YEAR TO MONTH)
insert into product values(INTERVAL '0-0' YEAR TO MONTH)
--
-- Data in Table
select * from product
--
-- Your query
SELECT
WARRANTY_PERIOD,
CASE
WHEN WARRANTY_PERIOD > INTERVAL '1-0' YEAR TO MONTH
THEN EXTRACT(YEAR FROM WARRANTY_PERIOD)
|| ' years '
|| CASE
WHEN EXTRACT(MONTH FROM WARRANTY_PERIOD) <> 0
THEN EXTRACT(MONTH FROM WARRANTY_PERIOD)
|| ' month'
END
WHEN WARRANTY_PERIOD > INTERVAL '0-1' YEAR TO MONTH
THEN EXTRACT(MONTH FROM WARRANTY_PERIOD)
|| ' month'
ELSE 'No warranty'
END AS WARRANTY
FROM
PRODUCT
输出
--
干杯!!
推荐阅读
- python - 抓取信息 - BeautifulSoup/Python
- rx-java2 - Micronaut/RxJava 控制器不向客户端返回输出
- javascript - replaceAll 不带替换 html 标签 JavaScript
- vba - 在 Powerpoint 中查找和删除文本
- ansible - 如何根据条件设置不同的参数
- stata - Stata:如何从病例对照研究的结果中生成数据集?
- ruby-on-rails - 除了名称属性之外,是否可以使用机械化复选框?
- python - 无法安装 pytorch:没有为 torch==1.7.0+cpu 找到匹配的发行版
- unity3d - 内置摄像头上的鼠标位置
- azure-cosmosdb - 带有 cosmos db 的 Asp.net 核心 api 中的 Json 补丁