2011-07-16 38 views
3

的最小值我在我的DB 3山坳,我想找到各方进行单个值如下explaind:表名:MyTable的如何找到在多个山坳

----------------------------- 
--id-- col1-- col2-- col3- 
----------------------------- 
    1  200 300  400 
    2  100 150  300 
    3  800 102  20 
    4  80  80  0 

我想要的结果out col1 col2 col3 = 0,这是其中的最小值。 是可能的!

我尝试:

select Min(col1, col2 , col3) as Tablemin 
from MyTable 
+0

一旦你得到结果,你可以轻松地在代码中做些什么?你必须在SQL中完成吗? –

回答

2

如果是MySQL或Oracle中,有LEAST()功能:

SELECT LEAST(MIN(col1), MIN(col2), MIN(col3)) 
     AS MinOfAllColumns 
FROM MyTable 

然后,有它在大多数RDBMS中使用的CASE声明:

SELECT CASE WHEN MIN(col1) <= MIN(col2) AND MIN(col1) <= MIN(col3) 
       THEN MIN(col1) 
      WHEN MIN(col2) <= MIN(col3) 
       THEN MIN(col2) 
       ELSE MIN(col3)    
     END 
     AS MinOfAllColumns 
FROM MyTable 

这也可以工作,但它很难得到其他领域与UNION方法:

SELECT MIN(col) AS MinOfAllColumns 
FROM 
    (SELECT MIN(col1) AS col 
    FROM MyTable 
    UNION 
    SELECT MIN(col2) 
    FROM MyTable 
    UNION 
    SELECT MIN(col3) 
    FROM MyTable 
) AS tmp 
+0

我试过了,但是我收到一个错误,说无法识别我在sql server中工作的语法商业智能有没有一个合适的语法为这个应用程序来建立我的查询。 – seeker

+0

@seeker:确切的错误是什么?语法是正确的。 –

+0

@ypercube,与联盟的答案已经存在。 –

6

ANSI SQL:

select min(col) 
from 
(
    select col1 [col] from MyTable 
    union all 
    select col2 from MyTable 
    union all 
    select col3 from MyTable 
)t 
+2

你可以只使用UNION,不需要UNION ALL。 – gbn

+1

您可以使用UNION,但更好地使用UNION ALL,速度更快。 –

1

SQLite中,答案很简单,只要:

SELECT MIN(MIN(col1), MIN(col2), MIN(col3)) FROM MyTable; 
2

简单的显示分钟的方法是:

string val = textBox2.Text; 
DataSet ds; 
con.Open(); 
string str = "SELECT * FROM Add_Rooms WHERE Price >= @price"; 
cmd = new SqlCommand(str, con); 
cmd.Parameters.AddWithValue("@price", val); 
SqlDataAdapter da = new SqlDataAdapter(cmd); 
ds = new DataSet(); 
da.Fill(ds, "Add_Rooms"); 
dataGridView1.DataSource = ds; 
dataGridView1.DataMember = "Add_Rooms"; 
con.Close();