偶然明智的订单计数

时间:2016-03-31 13:47:18

标签: sql sql-server set inner-join sql-like

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; =或子查询用作表达式时,不允许这样做。

1 个答案:

答案 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条件实际上是多余的。
  • 您应该使用ISO(YYYY-MM-DD)或SQL Server标准(YYYYMMDD)日期格式,而不是区域特定格式。
  • 缺乏有关基础数据的任何信息,如果&#34;产品&#34;那么您将面临获得笛卡尔积的风险。和&#34;详细信息&#34;是Order的独立维度。
相关问题