For each customer_id, I want to find the first delivery order. For each row of Delivery, I compare order_date with the smallest order_date of that customer_id.
Why does the SELECT statement below only return the row that contains the smallest order_date?
CREATE TABLE IF NOT EXISTS Delivery (
delivery_id int,
customer_id int,
order_date date,
customer_pref_delivery_date date
);
TRUNCATE TABLE Delivery;
INSERT INTO Delivery (delivery_id, customer_id, order_date, customer_pref_delivery_date)
VALUES (1, 1, '2019-08-01', '2019-08-02');
INSERT INTO Delivery VALUES (2, 2, '2019-08-02', '2019-08-02');
INSERT INTO Delivery VALUES (3, 1, '2019-08-11', '2019-08-12');
INSERT INTO Delivery VALUES (4, 3, '2019-08-24', '2019-08-24');
INSERT INTO Delivery VALUES (5, 3, '2019-08-21', '2019-08-22');
INSERT INTO Delivery VALUES (6, 2, '2019-08-11', '2019-08-13');
INSERT INTO Delivery VALUES (7, 4, '2019-08-09', '2019-08-09');
-- Write your PostgreSQL query statement below
WITH temp AS (
SELECT
d.delivery_id,
d.customer_id,
d.order_date,
d.customer_pref_delivery_date
FROM Delivery d
WHERE order_date = (SELECT MIN(order_date) FROM Delivery D
WHERE d.customer_id = D.customer_id)
)
select * from temp;
Input:
Delivery table:
+-------------+-------------+------------+-----------------------------+
| delivery_id | customer_id | order_date | customer_pref_delivery_date |
+-------------+-------------+------------+-----------------------------+
| 1 | 1 | 2019-08-01 | 2019-08-02 |
| 2 | 2 | 2019-08-02 | 2019-08-02 |
| 3 | 1 | 2019-08-11 | 2019-08-12 |
| 4 | 3 | 2019-08-24 | 2019-08-24 |
| 5 | 3 | 2019-08-21 | 2019-08-22 |
| 6 | 2 | 2019-08-11 | 2019-08-13 |
| 7 | 4 | 2019-08-09 | 2019-08-09 |
+-------------+-------------+------------+-----------------------------+
Output:
delivery_id | customer_id | order_date | customer_pref_delivery_date
-------------+-------------+------------+-----------------------------
1 | 1 | 2019-08-01 | 2019-08-02
(1 row)
Dand your aliasdare treated case-insensitive, so they are considered to be the same. Use a different alias for the table in your subquery. (Or explicitly quote them both, in both places - then they will be treated case-sensitive.)