SQL - 选择具有与其他行类似特征的表的行

时间:2015-10-22 16:17:37

标签: sql postgresql

我试图仅返回在某些列中具有类似答案的表的行,但不是所有列。例如:

我有下表,我试图只返回Frank和Joe正在吃同样的行' Meal'以及相同的' Time'和相同的位置'。

enter image description here

返回:

enter image description here

5 个答案:

答案 0 :(得分: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
    )

答案 1 :(得分: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

答案 2 :(得分:0)

您可以使用窗口函数按类似字段进行分组(在partition 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;

答案 3 :(得分: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)

答案 4 :(得分: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子句中指定的每一列。这些列是 table-free ,您可以在select-list中注意到。