MS SQL其中一列是x或y并且都返回

时间:2017-09-12 10:56:26

标签: sql sql-server

我在日期中有一个表格如下。该表格中有更多记录,但为了询问而简化:

Name     | Date       | Grade
Person 1 | 01-01-2001 | B
Person 1 | 31-01-2001 | A
Person 2 | 01-01-2001 | C
Person 3 | 31-01-2001 | A

我想返回Person 1的两个记录,但不返回其他两个记录。 AND显然没有返回任何东西,OR返回一切。我想搜索日期而非成绩

结果将是:

Name     | Date       | Grade
Person 1 | 01-01-2001 | B
Person 1 | 31-01-2001 | A

2 个答案:

答案 0 :(得分:3)

处理此问题的一种简单方法是按人员聚合,然后断言两个感兴趣的日期都存在:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT Name
    FROM yourTable
    WHERE Date IN ('2001-01-01', '2001-01-31')
    GROUP BY Name
    HAVING COUNT(DISTINCT Date) = 2
) t2
    ON t1.Name = t2.Name

答案 1 :(得分:1)

如果存在具有该名称的另一行,并且具有另一个A / B等级,则可以使用EXISTS返回一行。

select t1.*
from tablename t1
where t1.Date in ('2001-01-01', '2001-01-31')
  and exists (select 1 from tablename t2
              where t2.Name = t1.Name
                and t2.Date in ('2001-01-01', '2001-01-31')
                and t2.Date <> t1.Date)