2011-07-16 37 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();