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

How to get value from a query of another table to create a new column (postgresql)

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

第一个月的订单 table 如下所示。只显示当月用户第一次下的订单:

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

顺序table如下。显示所有订单记录:

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 

为了获取订单 table 中的第一个月订单列,我尝试使用如下案例。但是随后它会给出子查询返回的多行错误。

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 table?

使用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;

如果您在 orders table 中拥有所有订单,则不需要第二个 table。只需使用 window 函数。下面的 returns 一个布尔值,我觉得它比字符标志方便得多:

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;