我有一个产品订单表,我需要为每个订单找出特定客户的订单数量。假设 John Smith 通过电子邮件 john@smith.com 订购了 4 次,我需要为表中的每个订单添加一个数字,以表示该客户的订单数量。因此,电子邮件为 john@smith.com 的列表中的第 3 个订单将有一列显示 3。
我尝试使用一个子查询来计算每个客户的订单数量,但它会显示每个客户的相同订单数量,而不是该订单是否是第一、第二、第三等订单对于那个特定的客户。我运行的数据库是 Postgres。
SELECT
order_date,
email,
count as order_count
FROM (
SELECT
CAST(date_trunc('day', (order_order.created at time zone 'pst')) AS DATE) AS order_date,
order_order.email,
order_order.subscription_id,
count_orders.count
FROM
order_order
JOIN (
SELECT
order_order.email AS customer_email,
COUNT(*)
FROM
order_order
GROUP BY
order_order.email) AS count_orders ON order_order.email = count_orders.customer_email
ORDER BY
order_order.created DESC) b
ORDER BY
order_date DESC;
这是我想要返回的:
order_id email number_per_customer
======== ======= ==================
40 john@smith.com 4
30 john@smith.com 3
20 john@smith.com 2
10 john@smith.com 1
我目前得到的是:
order_id email number_per_customer
======== ======= ==================
40 john@smith.com 4
30 john@smith.com 4
20 john@smith.com 4
10 john@smith.com 4
最佳答案
我不知道您的查询与您的问题有什么关系。它引用了问题中未提及的一堆表和条件。
但是你似乎想要一个窗口函数。 根据文本这看起来像:
select o.*, row_number() over (partition by email order by order_id asc) as order_cnt
from orders o;
关于sql - 相对于表中相似行的数量向行添加计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58226782/