问题
I use the Informix database where I have a table coord :
+--------------------+-------------+
| Field | Type |
+--------------------+-------------+
| cm_key_coord_code | char(8) |
| cm_t_coor | int |
| descr_coord | char(30) |
+--------------------+-------------+
which contains data such as those shown below:
+-cm_key_coord_code-+-cm_t_coor-+-descr_coord-+
+ 00000001 + 1 + coord01a +
+ 00000001 + 2 + coord01b +
+ 00000002 + 1 + coord02a +
+ 00000002 + 2 + coord02b +
+ 00000003 + 1 + coord03a +
+ 00000004 + 2 + coord04a +
+ 00000005 + 1 + coord05a +
+-------------------+-----------+-------------+
The table has multiple record with same cm_key_coord_code, but different cm_t_coor. How can I select cm_key_coord_code that have only rows with cm_t_coor != 2 ?
I want to select only the following values:
+-cm_key_coord_code-+-cm_t_coor-+-descr_coord-+
+ 00000003 + 1 + coord03a +
+ 00000005 + 1 + coord05a +
+-------------------+-----------+-------------+
回答1:
SELECT t1.*
FROM Table t1,
( SELECT cm_key_coord_code
FROM Table
GROUP BY cm_key_coord_code
HAVING COUNT(*) = 1
) t2
WHERE t1.cm_key_coord_code = t2.cm_key_coord_code
AND t1.cm_t_coor <> 2;
回答2:
I would approach this using group by
and having
:
select c.cm_key_coord_code
from coord c
group by c.cm_key_coord_code
having sum(case when c.cm_t_coor = 2 then 1 else 0 end) = 0;
You can get the original rows in one of two ways. One method is to join the results together or (equivalently) using in
or exists
:
select c.*
from coord c
where c.cm_key_coord_code in (select c.cm_key_coord_code
from coord c
group by c.cm_key_coord_code
having sum(case when c.cm_t_coor = 2 then 1 else 0 end) = 0
);
Alternatively, if you know there is always only one row, you can use aggregation functions:
select c.cm_key_coord_code, min(cm_t_coor), min(descr_coord)
from coord c
group by c.cm_key_coord_code
having sum(case when c.cm_t_coor = 2 then 1 else 0 end) = 0
回答3:
You could do this with a NOT EXISTS clause as well. Try:
SELECT c.cm_key_coord_code
FROM coord c
WHERE NOT EXISTS
(SELECT 1
FROM coord c2
WHERE c2.cm_key_coord_code = c.cm_key_coord_code
AND c2.cm_t_coor = 2)
来源:https://stackoverflow.com/questions/40640610/sql-how-can-i-select-only-one-record-which-non-present-an-id