Declare OccasionName Varchar(100)
set @OccasionName=(select distinct (Message) from OrderProducts
where message like '%b''day%' or message like '%bday%' or Message like '%Birth%')
select Count(Distinct od.OrderID) as TotalOrders from orderdetails od
inner join (select Orderid,Message from OrderProducts) op on od.Orderid=op.OrderiD
where od.Orderdate between '01/01/2015' and '01/05/2015'
and op.Message like '%' + @OccasionName + '%'
and (od.TransactionId is not null) AND (od.TransactionId<>'')
这是错误:
子查询返回的值超过1。当子查询遵循=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询用作表达式时,不允许这样做。
答案 0 :(得分:1)
对于您认为想要完成的事情,您的查询似乎过于复杂。我认为这样做你想要的:
select Count(Distinct od.OrderID) as TotalOrders
from OrderDetails od inner join
OrderProducts op
on od.Orderid = op.OrderiD
where od.Orderdate between '2015-01-01' and '2015-05-01' and
od.TransactionId <> '' and
(op.message like '%b''day%' or
op.message like '%bday%' or
op.Message like '%Birth%'
);
注意:
OrderProducts
上的子查询是多余的。 SQL Server非常聪明,可以忽略它,但它可能会混淆其他数据库。is not null
条件实际上是多余的。Order
的独立维度。