请建议我一个查询,它只检索那些表中有单行的记录。例如:
**table1.** name age aaa 20 bbb 10 ccc 20 ddd 30
如果我运行“从table1中选择不同年龄。结果将是:
age 20 10 30
但我需要一个查询,其结果如
name age bbb 10 ddd 30
我使用DB2作为数据库。 谢谢......
答案 0 :(得分:1)
获得独特的年龄:
SELECT age
FROM table1
GROUP BY age
HAVING COUNT(*) = 1
要获取名称列,在MySQL中您只需添加列:
SELECT name, age
FROM table1
GROUP BY age
HAVING COUNT(*) = 1
然而,这个技巧在大多数其他数据库中都不起作用,我猜它在DB2中不起作用。相反,您可以使用MIN等聚合函数或带EXISTS,IN或JOIN的内部选择:
SELECT MIN(name), age
FROM table1
GROUP BY age
HAVING COUNT(age) = 1
或:
SELECT name, age
FROM table1
WHERE age IN (
SELECT age
FROM table1
GROUP BY age
HAVING COUNT(age) = 1
)
答案 1 :(得分:0)
SELECT name, age
FROM table1
GROUP BY age
HAVING COUNT(age)=1