我需要以这种格式进行格式化,以获取年数,月份及其组合的数量,或者“无保修”,具体取决于给定产品是否具有保修。我尝试使用case +提取,但是没有用
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”:
没有保修
答案 0 :(得分:2)
您可以使用以下内容:
-- 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
输出
-
干杯!
答案 1 :(得分:1)
只需在EXTRACT
语句中使用CASE
并在月份和/或年份为零时进行测试:
SELECT p.product_name,
SUM(o.quantity) AS total_quantity,
CASE
WHEN EXTRACT( MONTH FROM p.warranty_period ) = 0
AND EXTRACT( YEAR FROM p.warranty_period ) = 0
THEN 'No warranty'
WHEN EXTRACT( MONTH FROM p.warranty_period ) = 0
THEN EXTRACT( YEAR FROM p.warranty_period ) || ' years'
WHEN EXTRACT( YEAR FROM p.warranty_period ) = 0
THEN EXTRACT( MONTH FROM p.warranty_period ) || ' months'
ELSE EXTRACT( YEAR FROM p.warranty_period ) || ' years and '
|| EXTRACT( MONTH FROM p.warranty_period ) || ' months'
END AS WARRANTY
FROM PRODUCT_INFORMATION p
JOIN order_items o
ON p.product_id = o.product_id
GROUP BY
p.product_name,
p.warranty_period;