将两个选择查询合并为一个

时间:2018-09-03 09:19:38

标签: sql sql-server stored-procedures sql-server-2016

我有2个选择查询

select Amount,
       CurrentBalanceCurrency,
       AmountType
from UserBalance
where AmountType= 10

select Amount,
       CurrentBalanceCurrency,
       AmountType
from UserBalance
where AmountType= 20

我想在一行中进行此查询,而无需两次访问数据库。

4 个答案:

答案 0 :(得分:3)

IN子句中使用where运算符:

select Amount, CurrentBalanceCurrency, AmountType 
from UserBalance 
where AmountType in (10,20);

答案 1 :(得分:2)

您可以使用 IN 运算符。

查询

select [Amount], [CurrentBalanceCurrency], [AmountType]
from [UserBalance]
where [AmountType] in (10,20);

答案 2 :(得分:1)

您应该在这两个条件之间使用OR:

select Amount
,CurrentBalanceCurrency
,AmountType 
from UserBalance where AmountType= 10 OR AmountType = 20

答案 3 :(得分:0)

另一种选择是使用全部联合连接结果集,在某些情况下,这可以提高您必须自己进行测试):

select Amount,
       CurrentBalanceCurrency,
       AmountType
from UserBalance
where AmountType= 10
union all
select Amount,
       CurrentBalanceCurrency,
       AmountType
from UserBalance
where AmountType= 20