以下查询有效,但是“o.opendate不为null且o.orderdate不为null且o.closedate为null且o.canceldate为null”where子句的部分只需要应用于orderID计数(定单计数)。现在它正在应用于整个结果集,这不是我想要的。如何更改查询以执行此操作?这些表也非常大,所以我非常依赖索引,并且出于性能原因不尽量使用subquerys。任何帮助将不胜感激
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
答案 0 :(得分:3)
您需要一个包含 SUM 的案例陈述:
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 :(得分: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