Sql 如何在多个列中找到最小值
我的DB3列中有一个值,我想在所有这些值中找到一个值,如下所述:表名:MyTableSql 如何在多个列中找到最小值,sql,database,min,Sql,Database,Min,我的DB3列中有一个值,我想在所有这些值中找到一个值,如下所述:表名:MyTable ----------------------------- --id-- col1-- col2-- col3- ----------------------------- 1 200 300 400 2 100 150 300 3 800 102 20 4 80 80 0 我希望col1
-----------------------------
--id-- col1-- col2-- col3-
-----------------------------
1 200 300 400
2 100 150 300
3 800 102 20
4 80 80 0
我希望col1 col2 col3的结果是=0,这是其中的最小值。
有可能吗
我的尝试:
select Min(col1, col2 , col3) as Tablemin
from MyTable
如果是MySQL或Oracle,则有
LEAST()
函数:
SELECT LEAST(MIN(col1), MIN(col2), MIN(col3))
AS MinOfAllColumns
FROM MyTable
然后,有一个CASE
语句可以在大多数RDBMS中使用:
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
ANSI SQL:
select min(col)
from
(
select col1 [col] from MyTable
union all
select col2 from MyTable
union all
select col3 from MyTable
)t
在SQLITE中,答案很简单:
SELECT MIN(MIN(col1), MIN(col2), MIN(col3)) FROM MyTable;
显示最小值的简单方法是:
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();
我试过了,但收到一个错误,说我无法识别sql server business intelligence中使用的语法。这个应用程序是否有合适的语法来生成我的查询。@polishchuk:我知道,但它不一样。您可以使用UNION,然后分组查找MIN。您可以只使用UNION,而不需要使用UNION ALL。您可以使用UNION,但最好使用UNION ALL,这样会更快。这是一种在返回结果后可以在代码中轻松完成的操作吗?你必须用SQL来做吗?
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();