2013-02-22 51 views
0

下面的查询工作,但“o.opendate不是null o.orderdate不是null o.closedate是零和o.canceldate为空”的一部分where子句需要仅适用于将订单数(定单计数)。现在它适用于整个结果集,这不是我想要的。我如何更改查询来执行此操作?此外,这些表是非常大的,所以我对指标严重依赖,并尽量不使用性能方面的原因subquerys。任何帮助,将不胜感激添加where子句来算,而不是整个查询,而不使用子查询

select s.ZipCode, count(o.[OrderID]) orderCount, b.Longitude, b.Latitude, b.ordering 
from ZipCodeServiceAvailability s 
left join pdx_orders_view o on s.ZipCode = left(o.[ZipCode], 5) 
left join ZipCodeBoundaries b on s.ZipCode = b.ZipCode 
Where s.state = 'TX' and Ordering % 10 = 0 and 
    o.opendate is not null and o.orderdate is not null and o.closedate is null and o.canceldate is null 
Group By s.ZipCode, IsServiced, b.Longitude, b.Latitude, b.Ordering 
Order by s.ZipCode, b.Ordering 

回答

3

你需要用SUM case语句:

select sum(case when o.opendate is not null and o.orderdate is not null and o.closedate is null and o.canceldate is null 
      then 1 else 0 
     end) as OrderCount 

您应该然后从where条款中删除的条件。

+1

我认为你需要SUM()它以及得到计数。虽然很好的答案! – sgeddes 2013-02-22 16:15:41

+0

什么是当时的1否则为0?这笔钱会代替伯爵吗? – 2013-02-22 16:18:23

+2

'Then 1 Else 0'根据'Case'条件为每一行返回一个1或0,'包装'Case'语句的'Sum'添加这些值以获得应用于'案例'标准。 – 2013-02-22 16:24:51

1

你可以做你想做的与having子句。

select s.ZipCode, count(o.[OrderID]) orderCount, b.Longitude, b.Latitude, b.ordering 
from ZipCodeServiceAvailability s 
left join pdx_orders_view o on s.ZipCode = left(o.[ZipCode], 5) 
left join ZipCodeBoundaries b on s.ZipCode = b.ZipCode 
Where s.state = 'TX' and Ordering % 10 = 0 and 
    o.opendate is not null 
Group By s.ZipCode, IsServiced, b.Longitude, b.Latitude, b.Ordering 
Having count(o.[OrderID]) is not null 
Order by s.ZipCode, b.Ordering