optmize query以获取sql server中结果集末尾的总计

时间:2017-01-04 09:30:56

标签: sql sql-server optimization

我有一个产生以下结果的脚本:

期望的结果集: enter image description here

这是我使用的查询。

Select 
        SiteName, 
        (coalesce(country, '') + cast(row_number() over (partition by country order by country) as varchar(255))) Country, 
        Completed, 
        (Total - Completed-Deleted-Rejected) Remaining, 
      Deleted, 
        Total
from dbo.Statistics 
        where Date between '12/10/2016' and '12/29/2016' 
        and SiteName='pcltb.co.in'

union all

select 
        'Total', 
        'Total', 
        sum(Completed), 
        sum((Total - Completed-Deleted-Rejected)), 
        sum(Deleted),
        sum(Total)
from dbo.Statistics 
        where Date between '12/10/2016' and '12/29/2016' 
        and SiteName='pcltb.co.in'


现在,为了优化查询,我尝试使用ROLL UP和CUBE但无法获得所需的结果。

PS:我想在查询中使用UNION的替换或备用。

Pl建议。

2 个答案:

答案 0 :(得分:0)

您可以使用CTE。

with t as (Select 
        SiteName, 
        (coalesce(country, '') + cast(row_number() over (partition by country order by country) as varchar(255))) Country, 
        Completed, 
        (Total - Completed-Deleted-Rejected) Remaining, 
      Deleted, 
        Total
from dbo.Statistics 
        where Date between '12/10/2016' and '12/29/2016' 
        and SiteName='pcltb.co.in')
select * from t
union all
select 'Total', 'Total',
        sum(Completed), 
        sum(Remaining), 
        sum(Deleted),
        sum(Total)
from t group by SiteName, Country;

这将读取表格一次,并对已计算的值应用总和。

答案 1 :(得分:0)

find_or_create
sitename    Country     Complete    Reminning   Deleted     Total
----------- ----------- ----------- ----------- ----------- -----------
pcltb.co.in 1           34          0           1           35
pcltb.co.in 2           48          0           1           35
Total       Total        82          0           2           70