我已根据建议修改了代码,但现在性能已经下降。欢迎任何建议
select *
from (
SELECT
d.ID,
d.HeaderId,
CASE WHEN h.MyType = 'C' THEN
RANK() OVER (PARTITION BY l.Work ORDER BY l.Address1 DESC)
ELSE
RANK() OVER (PARTITION BY l.Home ORDER BY l.Address1 DESC)
END
AS 'RANK',
CASE WHEN h.MyType = 'C' THEN
COUNT(l.Work) OVER (PARTITION BY l.Work)
ELSE
COUNT(l.Home) OVER (PARTITION BY l.Home)
END
AS 'MAXCOUNT'
FROM schema1.Details AS d
JOIN schema1.BatchHeader AS h
ON d.HeaderId = h.ID
JOIN schema2.Details AS l
ON d.LeadBatchDetailId = l.Id
LEFT JOIN LDCs AS ldcElec
ON l.LDC_Elec = schema3.Code
LEFT JOIN LDCs AS ldcGas
ON l.ldc_gas = ldcGas.Code
LEFT JOIN schema2.Accounts ag
ON (l.Work = ag.Phone AND 'G' = ag.Business AND h.MyType = 'C')
OR (l.Home = ag.Phone AND 'G' = ag.Business AND h.MyType = 'R')
LEFT JOIN schema2.Accounts ae
ON (l.Work = ae.Phone AND 'E' = ae.Business AND h.MyType = 'C')
OR (l.Home = ae.Phone AND 'E' = ae.Business AND h.MyType = 'R')
WHERE d.HeaderId = @Id)
) a
WHERE [RANK] = [MAXCOUNT]
ORDER BY LdcGasName, LdcElecName
答案 0 :(得分:0)
我不相信SQL会这样做,支持在排名函数中嵌入的AND型逻辑。您可能需要将其分解为更多子查询。一些极端的伪代码:
但是你必须处理COUNT ... OVER ...,而且这个数量不依赖于h.MyType = C或R,这让我想知道MAXCOUNT是否会最终使得排名值等于是如此受限制。
这一切都假设我正在读它......但这是一个复杂的查询,如果不了解底层表和业务逻辑就很难理解。