如何选择具有相同列条件的多行

时间:2019-03-20 23:43:10

标签: sql oracle

如何选择具有相同列条件的多行?

Name    Plat
 Bob       1
 Kay       2
 Sih       3

我有Bob和Kay这两个参数。因此,我需要检索Bob和Kay的记录。如果表中不存在Bob或Kay,则返回空。如果表中存在Bob和Kay,则显示两个记录。

以下sql对我不起作用

Select * from table where Name = 'Bob' And Name = 'Kay'

有帮助吗?

4 个答案:

答案 0 :(得分:2)

您可以尝试将existsHAVING条件汇总函数一起使用。

CREATE TABLE T(
   Name VARCHAR(5),
   Plat int
);

INSERT INTO T VALUES ('Bob',1);
INSERT INTO T VALUES ('Kay',2);
INSERT INTO T VALUES ('Sih',3);
INSERT INTO T VALUES ('Sih',4);
INSERT INTO T VALUES ('Bob1',1);

查询1

SELECT *
FROM T t1
WHERE exists(
  SELECT 1
  FROM T tt
  WHERE t1.Name in ('Bob','Sih')
  HAVING 
      SUM(CASE WHEN Name = 'Bob' THEN 1 END) > 0
  AND
      SUM(CASE WHEN Name = 'Sih' THEN 1 END) > 0
)

Results

| NAME | PLAT |
|------|------|
|  Bob |    1 |
|  Sih |    3 |
|  Sih |    4 |

答案 1 :(得分:1)

这假设鲍勃和凯在表中是唯一的

  Select * from table 
   where Name IN ('Bob', 'Kay') 
     and ( select count(*) from table where Name IN ('Bob', 'Kay')) = 2

答案 2 :(得分:0)

Select * from table where Name = 'Bob' OR Name = 'Kay'

您要选择名称='Bob' OR 或名称='Kay'的行。请记住,SQL是按行应用的,因此名称不能同时等于'Bob'和'Kay'。

答案 3 :(得分:0)

我将使用时态表执行该操作,如下所示:

DECLARE @First NVARCHAR(50) = 'Bob';
DECLARE @Last NVARCHAR(50) = 'Kay';

SELECT *
INTO #TempSearch
FROM table
WHERE (Name = @First OR Name = @Last)

SELECT
    COUNT(*) AS Total,
    (SELECT COUNT(a.Name) FROM table AS a WHERE Name = @First) AS TotalByFirst,
    (SELECT COUNT(b.Name) FROM table AS b WHERE Name = @Last) AS TotalByLast
INTO #TempTotal
FROM #TempSearch

SELECT ts.*
FROM #TempTotal AS t, #TempSearch AS ts
WHERE t.Total = (t.TotalByFirst + t.TotalByLast)
AND t.TotalByFirst > 0 AND t.TotalByLast > 0

DROP TABLE #TempTotal
DROP TABLE #TempSearch