Table layout:
CREATE TABLE t_order (id INT, custId INT, order DATE)
I’m looking for a SQL command to select a maximum of one row per order (the customer who owns the order is identified by a field named custId).
I want to select ONE of the customer’s orders (doesn’t matter which one, say sorted by id) if there is no order date given for any of the rows.
I want to retrieve an empty Resultset for the customerId, if there is already a record with given order date.
Here is an example. Per customer there should be one order at most (one without a date given). Orders that have already a date value should not appear at all.
+---------------------------------------------------------+ |id | custId | date | +---------------------------------------------------------+ | 1 10 NULL | | 2 11 2008-11-11 | | 3 12 2008-10-23 | | 4 11 NULL | | 5 13 NULL | | 6 13 NULL | +---------------------------------------------------------+ | | | Result \ | / \ / +---------------------------------------------------------+ |id | custId | date | +---------------------------------------------------------+ | 1 10 NULL | | | | | | | | 5 13 NULL | | | +---------------------------------------------------------+ powered be JavE
Edit: I’ve choosen glavić’s answer as the correct one, because it provides the correct result with slightly modified data:
+---------------------------------------------------------+ |id | custId | date | +---------------------------------------------------------+ | 1 10 NULL | | 2 11 2008-11-11 | | 3 12 2008-10-23 | | 4 11 NULL | | 5 13 NULL | | 6 13 NULL | | 7 11 NULL | +---------------------------------------------------------+
Sfossen’s answer will not work when customers appear more than twice because of its where clause constraint a.id != b.id.
Quassnoi’s answer does not work for me, as I run server version 4.0.24 which yields the following error: alt text http://img25.imageshack.us/img25/8186/picture1vyj.png
Try this:
For MySQL 4: