带有columns id, order_number, location
的表
数据看起来像
[1, 123, 'texas']
[2, 123, 'ny']
[3, 456, 'texas']
[4, 456, 'ny']
[5, 678, 'hawaii']
我想从id
中选择与ny
中具有相同order_number
的记录texas
答案 0 :(得分:0)
一种选择是使用EXISTS
子句:
SELECT id
FROM yourTable t1
WHERE location = 'ny' AND EXISTS (SELECT 1 FROM yourTable t2
WHERE t1.order_number = t2.order_number AND
t2.location = 'texas');
编辑::如果您想使用聚合方法,也可以:
SELECT MAX(CASE WHEN location = 'ny' THEN id END) AS id
FROM yourTable
WHERE location IN ('ny', 'texas')
GROUP BY order_number
HAVING COUNT(DISTINCT location) = 2;
在这里,我们可以按order_number
进行汇总,然后将纽约的id
值作为枢纽。