【问题标题】:optmize query to get the grand total at the end of the result set in sql server优化查询以获取 sql server 中结果集末尾的总计
【发布时间】:2017-01-04 17:42:03
【问题描述】:

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

所需的结果集:

这是我使用的查询。

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。

请建议。

【问题讨论】:

  • 请避免在显示结果时使用图像,将预期结果粘贴为文本,当前结果
  • SQL Server 是一个数据库管理系统,最适合存储和检索数据,对于数据展示,我们有其他报告工具,如 SSRS、Qlikview 等,使用适当的工具进行数据展示 SQL Server 不是为这个。

标签: sql sql-server optimization


【解决方案1】:

您可以使用 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;

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

【讨论】:

    【解决方案2】:
        ;WITH tb(sitename,Country,Complete,Reminning,Deleted,Total)AS
        (
           SELECT 'pcltb.co.in',1,34,0,1,35 UNION
           SELECT 'pcltb.co.in',2,48,0,1,35
        )
        SELECT ISNULL(sitename,'Total') AS sitename,ISNULL(Country,'Total') as Country,SUM(Complete) AS Complete,SUM(Reminning) AS Reminning,SUM(Deleted) AS Deleted,SUM(Total) AS Total 
    
        FROM tb
        GROUP BY sitename,Country
        WITH ROLLUP
        HAVING GROUPING(sitename)=GROUPING(Country)
    
    站点名称 国家 完成 提醒 删除 总计 ----------- ------------ ----------- ----------- ------ ----- ------------ pcltb.co.in 1 34 0 1 35 pcltb.co.in 2 48 0 1 35 总计 总计 82 0 2 70

    【讨论】:

      猜你喜欢
      • 2011-03-26
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      • 1970-01-01
      相关资源
      最近更新 更多