简体   繁体   English

使SQL查询运行更快

[英]Make sql query run faster

Is it possible to make some optimization on such query ? 是否可以对此类查询进行一些优化?

with t (CurrentPrice, [Weight])
as ( select CurrentPrice, [Weight] from SomeTable where GroupingId = SomeBigIntId )

SELECT MaxExactPrice = ( select MAX(CurrentPrice) FROM t Where [Weight] > 0 ),  
   MinExactPrice = ( select MIN(CurrentPrice) FROM t Where [Weight] > 0 ),
   MaxSimilarPrice = ( select MAX(CurrentPrice) FROM t Where [Weight] = 0 ),
   MinSimilarPrice = ( select MIN(CurrentPrice) FROM t Where [Weight] = 0 ),
   ExactCount = ( select Count(*) FROM t Where [Weight] > 0 ),
   SimilarCount = ( select Count(*) FROM t Where [Weight] = 0 ),
   Count(*) as TotalCount
FROM t

Thank you. 谢谢。

Do this instead. 改为这样做。 this way you do not have to hit same table 8 different times. 这样,您不必在8次不同的时间打同一张桌子。

select MAX(CASE WHEN [Weight] > 0 THEN CurrentPrice ELSE NULL END) AS MaxExactPrice
,MIN(CASE WHEN [Weight] > 0 THEN CurrentPrice ELSE NULL END) AS MinExactPrice
,MAX(CASE WHEN [Weight] = 0 THEN CurrentPrice ELSE NULL END) AS MaxSimilarPrice
,MIN(CASE WHEN [Weight] = 0 THEN CurrentPrice ELSE NULL END) AS MinSimilarPrice
,COUNT(CASE WHEN [Weight] > 0 THEN 1 ELSE NULL END ) AS ExactCount
,COUNT(CASE WHEN [Weight] = 0 THEN 1 ELSE NULL END ) AS SimilarCount
,COUNT(*)AS TotalCount
from SomeTable where GroupingId = SomeBigIntId 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM