如果您不需要实际使用行号,那么我会选择 TOP 1 行。查询可以简化很多。我喜欢首先从表中选择最能被您的谓词过滤掉的表。希望您对 frs.fundraiserid 和参与连接的所有列都有一个良好的索引。
SELECT
TOP 2 customercampaignname + ' $' + CONVERT(VARCHAR(255), CAST(SUM(d.mastercurrencyamount) AS NUMERIC(36,2) ) ) AS 'Check_Stub_Comment2',
ROW_NUMBER() OVER(ORDER BY SUM(d.mastercurrencyamount) DESC) as rownumber
FROM bb02_fundraiserrevenuestream frs
JOIN bb02_donationline dl ON
dl.fundraiserrevenuestreamid = frs.fundraiserrevenuestreamid
JOIN bb02_donation d ON
d.donationid = dl.donationid
WHERE frs.fundraiserid = 1869
AND d.customercampaignname IS NOT NULL
AND d.customercampaignname != ''
GROUP BY d.CustomerCampaignName
ORDER BY SUM(d.mastercurrencyamount) DESC
由于您需要能够选择第一行或第二行,因此将其包装在 CTE 或子查询中。
WITH topcampaign AS (
SELECT
TOP 2 customercampaignname + ' $' + CONVERT(varchar(255), CAST(SUM(d.mastercurrencyamount) AS NUMERIC(36,2) ) ) AS 'Check_Stub_Comment2',
ROW_NUMBER() OVER(ORDER BY SUM(d.mastercurrencyamount) DESC) as rownumber
FROM bb02_fundraiserrevenuestream frs
JOIN bb02_donationline dl ON
dl.fundraiserrevenuestreamid = frs.fundraiserrevenuestreamid
JOIN bb02_donation d ON
d.donationid = dl.donationid
WHERE frs.fundraiserid = 1869
AND d.customercampaignname IS NOT NULL
AND d.customercampaignname != ''
GROUP BY d.CustomerCampaignName
ORDER BY SUM(d.mastercurrencyamount) DESC
)
SELECT * from topcampaign WHERE rownumber = 1
作为另一种可能的优化,我将 CONVERT 从 CTE 中取出并放入最终选择中。不确定这是否有很大帮助。
WITH topcampaign AS (
SELECT
TOP 2
customercampaignname,
SUM(d.mastercurrencyamount) AS amount,
ROW_NUMBER() OVER(ORDER BY SUM(d.mastercurrencyamount) DESC) as rownumber
FROM bb02_fundraiserrevenuestream frs
JOIN bb02_donationline dl ON
dl.fundraiserrevenuestreamid = frs.fundraiserrevenuestreamid
JOIN bb02_donation d ON
d.donationid = dl.donationid
WHERE frs.fundraiserid = 1869
AND d.customercampaignname IS NOT NULL
AND d.customercampaignname != ''
GROUP BY
d.CustomerCampaignName
ORDER BY
SUM(d.mastercurrencyamount) DESC
)
SELECT
rownumber,
customercampaignname + ' $' + CONVERT(varchar(255), CAST(amount AS NUMERIC(36,2) ) ) AS 'Check_Stub_Comment2'
FROM topcampaign
WHERE rownumber = 1