[英]Union all customers from two tables and assign date values from second table in case customer does not exist in first table
CREATE TABLE sales
(
id SERIAL PRIMARY KEY,
last_order DATE,
customer VARCHAR(255)
);
INSERT INTO sales (last_order, customer)
VALUES
('2020-09-10', 'user_01'),
('2020-10-15', 'user_02'),
('2020-11-26', 'user_03');
CREATE TABLE customers
(
id SERIAL PRIMARY KEY,
first_order DATE,
customer VARCHAR(255)
);
INSERT INTO customers (first_order, customer)
VALUES
('2020-08-10', 'user_01'),
('2020-09-15', 'user_02'),
('2020-10-17', 'user_03'),
('2020-05-03', 'user_04'),
('2020-04-12', 'user_05');
Expected result:预期结果:
customer | used_date |
-----------|----------------|------
user_01 | 2020-09-10 |
user_02 | 2020-10-15 |
user_03 | 2020-11-26 |
user_04 | 2020-05-03 |
user_05 | 2020-04-12 |
I have two tables and I want to query all customers in both tables.我有两个表,我想查询两个表中的所有客户。
Additionally, in case the customer does not exist in the table sales
I want to apply the first_order
from table customers
as used_date
.此外,如果客户在表
sales
中不存在,我想将表customers
中的first_order
应用为used_date
。
So far I came up with this query:到目前为止,我想出了这个查询:
SELECT
t1.customer,
(CASE WHEN t1.last_order IS NULL THEN t1.first_order ELSE t1.last_order END) AS used_date
FROM
(SELECT
s.customer,
s.last_order AS last_order,
NULL::date AS first_order
FROM
sales s
GROUP BY
1, 2, 3
UNION ALL
SELECT
c.customer,
NULL::date AS last_order,
c.first_order AS first_order
FROM
customers c
GROUP BY
1, 2, 3) t1
GROUP BY
1, 2
ORDER BY
1;
How do I need to modify the CASE WHEN
statement to get the expected result?如何修改
CASE WHEN
语句以获得预期结果?
This looks like a left join
:这看起来像
left join
:
select c.*,
coalesce(s.last_order, c.first_order) as used_date
from customers c left join
sales s
on c.customer = s.customer;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.