如何从另一个表的查询中获取值以创建新列(postgresql)

时间:2020-12-22 05:16:43

标签: sql postgresql case

我是 postgres 的新手,如果订单(订单表)是第一个月订单(第一个月订单表),我希望能够将值设置为 Y

第一个月的订单表如下。它只会显示当月第一次用户下的订单:

customer_id | order_date                | order_id
--------------------------------------------------
a1          | December 6, 2015, 8:30 PM | orderA1

订单表如下。它显示了所有的订单记录:

customer_id | order_date                 | order_id
-----------------------------------------------------
a1          | December 6, 2020, 8:30 PM  | orderA1 
a1          | December 7, 2020, 8:30 PM  | orderA2 
a2          | December 11, 2020, 8:30 PM | orderA3 

为了获取订单表中的第一个月订单列,我尝试使用 case 如下。但随后它会给错误超过一个子查询返回的行。

SELECT DISTINCT ON (order_id) order_id, customer_id,
(CASE when (select distinct order_id from first_month_order_table) = order_id then 'Y' else 'N'
 END)
FROM order_table
ORDER BY order_id;

我也尝试过使用计数,但后来我明白这是非常低效的,而且我认为数据库会过度使用。

SELECT DISTINCT ON (order_id) order_id, customer_id,
(CASE when (select count order_id from first_month_order_table) then 'Y' else 'N'
 END)
FROM order_table
ORDER BY order_id;

如何有效判断订单是否为首月订单,并将订单表中的每个订单的值都设置为Y?

2 个答案:

答案 0 :(得分:1)

使用 left join 如下:

SELECT o.order_id, o.customer_id,
       CASE when f.order_id is not null then 'Y' else 'N' END as flag
FROM order_table o left join first_month_order_table f
  on f.order_id = o.order_id 
ORDER BY o.order_id;

答案 1 :(得分:1)

如果您在 orders 表中有所有订单,则不需要第二个表。只需使用窗口函数。以下返回一个布尔值,我发现它比字符标志方便得多:

select o.*,
       (row_number() over (partition by customer_id, date_trunc('month', order_date order by order_date) = 1) as flag
from orders o;

如果你想要一个字符标志,那么你需要case

select o.*,
       (case when row_number() over (partition by customer_id, date_trunc('month', order_date order by order_date) = 1
             then 'Y' else 'N'
        end) as flag
from orders o;
相关问题