我有两张桌子:
我需要选择在加入日期后6个月内下订单的客户数量 到目前为止我做了什么:
SELECT COUNT(*)
FROM customers
JOIN orders
ON customers.id = orders.customer_id
AND (
orders.order_date BETWEEN customers.joining_date
AND DateAdd(month,1,customers.joining_date)
)
但我得到了
Error: column 'month' does not exist
答案 0 :(得分:1)
您正在使用SQL Server语法
在PostgreSQL中,您添加date + interval '1 month'
的间隔
因此,在您的情况下,您应该通过以下方式替换DateAdd:
customers.joining_date + interval '6 month'
答案 1 :(得分:1)
使用此查询使用PostgreSQL语法表达式:
SELECT COUNT(*)FROM customers JOIN orders ON customers.id = orders.customer_id AND(orders.order_date BETWEEN customers.joining_date AND(customers.joining_date + INTERVAL'1 月'));
答案 2 :(得分:0)
您的逻辑(尝试)计算订单的数量,而不是客户的数量。这有两种方法:
SELECT COUNT(DISTINCT c.id)
FROM customers c JOIN
orders o
ON c.id = o.customer_id AND
o.order_date >= c.joining_date AND
o.order_date < c.joining_date + interval '6 month';
或者更有效率:
SELECT COUNT(*)
FROM customers c
WHERE EXISTS (SELECT 1
FROM orders o
WHERE c.id = o.customer_id AND
o.order_date >= c.joining_date AND
o.order_date < c.joining_date + interval '6 month'
);