【发布时间】:2013-07-22 18:36:01
【问题描述】:
此查询平均需要 4 秒。它将成为存储过程中的子查询,我需要它花费一秒。这是查询:
(select customercampaignname + ' $' + convert(varchar, cast(amount as numeric(36,2) ) ) As 'Check_Stub_Comment2' from (
select ROW_NUMBER() OVER (ORDER BY amount desc) as rownumber, customercampaignname, amount from (
select * from (
select distinct d.customercampaignname
,sum(d.mastercurrencyamount) As amount
from bb02_donation d
JOIN bb02_donationline dl on d.donationid = dl.donationid
JOIN bb02_fundraiserrevenuestream frs on dl.fundraiserrevenuestreamid = frs.fundraiserrevenuestreamid and frs.fundraiserid = 1869
where d.customercampaignname is not null
and d.customercampaignname != ''
group by d.CustomerCampaignName
) as x
) as sub ) as y where rownumber = 1)
【问题讨论】:
-
澄清 - “where rownumber =”很重要。我需要能够仅选择第 1 行,或仅选择第 2 行。
-
我在下面标记的答案确实使这个查询更快,但是它仍然是对数据库的 n+ 调用。就我而言,我只关心 2 个结果,所以我将它们存储到一个临时表中,只需调用一次数据库。然后我能够从临时表中取出前 1 个结果,对其进行排序,然后再次取出前 1 个结果。这将我的总查询时间减少了一半。谢谢大家的回复。
标签: sql sql-server subquery query-optimization