在ONE查询中为id和整个表选择最小值

时间:2013-05-06 12:54:26

标签: sql sql-standards

我想找到特定ID的最低访问值,以及整个表的最低访问值。 在一个查询中。

MYTAB

ID  VISITED
101 2009
102 2010
103 2011
104 2012
105 2013

我可以在一个查询中执行此操作吗?

现在我喜欢:

select
  min(visited)
from
  mytab
where
  id = 100;

然后我进行第二次查询。

select
  min(visited)
from
  mytab;

我想要的是下面的内容(但是可以让它变得更简单吗?)

select 
  min( a.visited ),
  min( b.visited )
from
  (select visited from mytab where id=100) as a,
  (select visited from mytab) as b;

Query run for e.g. id 103 and 100 would be:
id 103 will give 2011,2009
id 100 will give null,2009 

由于

2 个答案:

答案 0 :(得分:1)

select  min(visited) as GlobalMin
,       min(case when id = 100 then visited end) as MinForId100
from    mytab

答案 1 :(得分:1)

您可以将MINCASE

一起使用
select 
    min(case when id = 100 then visited end) minbyid,
    min(visited) minoverall
from mytab

SQL Fiddle Demo