sql - 对所有结果进行分组 SQL Server

标签 sql sql-server group-by union-all

我是 SQL Server 新手。我有一个 SQL 查询,我执行了所有联合操作,两个单独的查询有分组依据。

select top 5  
    Starttime, convert(date,row_date) as Date,
    sum(acdcalls + abncalls) [Offered],
    sum(acdcalls) [Handled],
    sum(abncalls) [Abandoned],
    sum(acdcalls1 + acdcalls2 + acdcalls3 + acdcalls4 + acdcalls5) [Answered within SLA],
    case 
        when sum(acdcalls) != 0 
          then cast((sum(acdcalls1 + acdcalls2 + acdcalls3 + acdcalls4 + acdcalls5)) * 1.0 / sum((acdcalls)) * 1.0 * 100 as decimal(10, 2)) 
          else 0 
    end as [SLA in %]
from 
    db1
where 
    row_date = getdate()
group by 
    Starttime, row_Date

union all

select top 5 
    Starttime, convert(date,row_date) as Date,
    sum(acdcalls + abncalls) [Offered],
    sum(acdcalls) [Handled],
    sum(abncalls) [Abandoned],
    sum(acdcalls1 + acdcalls2 + acdcalls3 + acdcalls4 + acdcalls5) [Answered within SLA],
    case 
       when sum(acdcalls) != 0 
         then cast((sum(acdcalls1 + acdcalls2 + acdcalls3 + acdcalls4 + acdcalls5)) * 1.0 / sum((acdcalls)) * 1.0 * 100 as decimal(10, 2)) 
         else 0 
    end as [SLA in %]
from 
    db2
where 
    row_date = getdate()
group by 
    Starttime, row_Date

Starttime 列具有通用值。我想对结果进行分组 Starttime 。我怎样才能做到这一点?任何帮助将不胜感激

最佳答案

您需要先进行并集,然后再进行聚合。以下示例使用子查询,但如果您愿意,也可以使用临时表:

Select StartTime, Row_Date, sum(acdcalls+abncalls)...[other sums here]
  From (
    select * from db1 
    union all
    select * from db2
  ) a
group by StartTime, RowDate

如果需要,您仍然可以在子查询中包含 where 子句和特定列(上面的示例仅在 db1 和 db2 具有相同顺序的相同列时才有效 - 否则您将需要指定您的列)。不过,如果您将两个选择限制为 Row_Date = GetDate(),我不确定为什么要按 Row_Date 分组。

关于sql - 对所有结果进行分组 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29993173/

相关文章:

json - jq 在许多单独的文件中创建输出

sql - 如何编写更新触发器以根据 SQL Server 2008 中另一个表中的值更新当前表?

php - 单击选项卡时如何将 sql 的结果显示到列表中?

c# - 动态创建数据集并传递给 ReportViewer

MYSQL统计同一个表中某个问题的答案数

laravel-5 - laravel 使用 Distinct Eloquent 关系

SQL选择具有相同值的连续记录

sql - 更新列以删除 SQLite 中之前的所有内容并包括空格

mysql - 一行内匹配不同值 II

当 PIVOT 在 SQL Server CE 中不可用时的 SQL 等效项