2015-10-22 98 views
2

我想只返回在某些列(但不是所有列)中具有類似答案的表的行。例如:SQL - 選擇與其他行具有相似特徵的表的行

我有下表,我試圖返回弗蘭克和喬正在吃同樣的'餐',和相同的'時間',和相同的'位置'的行。

enter image description here

返回此:

enter image description here

+0

[你有什麼試過?](http://mattgemmell.com/what-have-you-tried/) – Pred

+0

擱置?我發現這個問題很清楚... – jarlh

回答

0

我想你要找的是什麼IN子句:

SELECT * FROM my_table 
WHERE Attendee IN ('Frank', 'Joe') 
AND Meal = 'Lunch' 
AND Time = '12:00' 
AND Location = 'Cafeteria' 

http://www.postgresqltutorial.com/postgresql-in/

編輯:選擇他們所有的行共享一個公共餐,時間和位置(而不僅僅是一個),試試這個:

SELECT * FROM my_table t1 WHERE Attendee = 'Frank' 
JOIN (SELECT * FROM my_table t2 WHERE Attendee = 'Joe') 
    ON (t1.Meal = t2.Meal 
     AND t1.Time = t2.Time 
     AND t1.Location = t2.Location 
    ) 
+0

這裏的問題是,我在任何時間,任何地點尋找任何餐點......只要弗蘭克和喬都在那裏。 – illiller

+0

我添加了一個使用'INNER JOIN'的更一般的版本。 – McGlothlin

+0

太棒了。謝謝! – illiller

0

您可以使用intersect做到這一點。

select * from tablename 
where (meal, time, location) in 
(
select meal, time, location from tablename where attendee = 'Frank' 
intersect 
select meal, time, location from tablename where attendee = 'Joe' 
) t 
0

您可以使用窗口功能,通過類似領域(BY子句中的分區)組,然後限制你的記錄那些具有多個記錄:

SELECT ApptID, Meal, Time, Location, Attendee 
FROM ( SELECT ApptID, 
        Meal, 
        Time, 
        Location, 
        Attendee, 
        COUNT(*) OVER(PARTITION BY Meal, Time, Location) AS CountOfOccurrences 
      FROM T 
     ) AS T 
WHERE CountOfOccurrences > 1; 
0

您可以使用一個內連接來概括您的查詢並獲取不同參與者的相同列值(在此情況下爲膳食,時間,地點)的所有匹配。事情是這樣的:

select tb1.attendee, tb1.location, tb1.time, tb1.meal 
from yourtbable as tb1 
inner join yourtbable as tb2 
on (tb1.meal = tb2.meal 
    and tb1.location = tb2.location 
    and tb1.time = tb2.time 
    and tb1.attendee <> tb2.attendee) 
0

另一種解決方案 - 不是SQL精彩 - 有這麼多不同的方式:

select tf.name, tj.name, meal, time, location 
from (select * from tablename where attendee = 'Frank') tf 
join (select * from tablename where attendee = 'Joe') tj using (meal, time, location) 

的加入的USING (meal, time, location)語法基本相同ON tf.meal = tj.meal AND tf.time = tj.time AND tf.location = tj.location,但不同的結果只有USING條款中指定的每個列。這些列是免表,您可以在選擇列表中注意到。

相關問題