是否可以对此类查询进行一些优化?
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
谢谢。
答案 0 :(得分:3)
这样做。通过这种方式,您不必在不同时间点击同一个表格。
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