SQL获得第一个匹配结果

时间:2012-06-25 19:37:40

标签: sql asp-classic odbc netezza

我有以下SQL语句:

SELECT ID, NAME FROM myTable
WHERE 
ID LIKE 'R43%' OR 
ID LIKE 'D32%' OR 
ID LIKE 'F22%'

和ID可能包含以下值:

ID
____

R431
R431
R432
R434
D322
D322
D327
F226
F227

我如何才能获得匹配的第一个ID的记录?与上面的值一样,我只会得到(R431,R431,D322,D322,F226)的记录。我正在抓取的表格中的ID值是顺序的(因此R432将始终出现在表格中的R431之后)。

4 个答案:

答案 0 :(得分:3)

将Oracle Analytical函数用于此类查询

    select * from (
select id , substr(id,0,3),rank() over ( partition by substr(id,0,3) order by id) rank 
from mytable
WHERE ID LIKE 'R43%' OR ID LIKE 'D32%' OR ID LIKE 'F22%')
where rank = 1

答案 1 :(得分:0)

MIN查询和嵌套子查询的组合应该可以满足您的需求。

Select ID, 
       Name 
FROM myTable 
WHERE 
     ID IN ( 
       SELECT MIN(ID) From myTable WHERE ID LIKE 'R43%' OR  ID LIKE 'D32%' OR  ID LIKE 'F22%'     
           )

如果您要关闭另一个字段,例如OrderDate等,请更改子查询。无论哪种方式,外部查询将仅从内部查询中选择的ID中选择记录。

答案 2 :(得分:0)

使用DISTINCT:

SELECT DISTINCT ID, NAME FROM myTable
WHERE 
ID LIKE 'R43%' OR 
ID LIKE 'D32%' OR 
ID LIKE 'F22%'

答案 3 :(得分:0)

尝试使用子查询:

SELECT R.ID AS ID, R.NAME AS NAME FROM myTable R
WHERE 
R.ID LIKE 'R43%'
AND R.ID IN 
(
  SELECT DISTINCT A.ID
 FROM myTable A
 WHERE A.ID LIKE 'R43%'
 ORDER BY A.ID
 LIMIT 1
)

UNION 

SELECT D.ID AS ID, D.NAME AS NAME FROM myTable D
WHERE  
D.ID LIKE 'D32%'
AND D.ID IN 
(
  SELECT DISTINCT B.ID
 FROM myTable B
 WHERE B.ID LIKE 'D32%'
 ORDER BY B.ID
 LIMIT 1
)

UNION

SELECT F.ID AS ID, F.NAME AS NAME FROM myTable F
WHERE  
F.ID LIKE 'F22%'
AND F.ID IN 
(
  SELECT DISTINCT C.ID
 FROM myTable C
 WHERE C.ID LIKE 'F22%'
 ORDER BY C.ID
 LIMIT 1
)