简体   繁体   English

汇总不同临时表中的数据

[英]summing data in different temp tables

I have 2 temp tables inside a procedure having data like see at the bottom of this ost.我在一个过程中有 2 个临时表,其中的数据就像在这个 ost 的底部看到的一样。

In temporary table table 1 I have phone tickets for each category and each department d1 and d2.在临时表table 1我有每个类别和每个部门 d1 和 d2 的电话票。

Similarly in temporary table Table 2 I have IVR tickets for each category and each department d1 and d2.同样在临时Table 2我有每个类别和每个部门 d1 和 d2 的 IVR 票。

Now I need to sum phone and IVR tickets and show as another temp table.现在我需要总结电话和 IVR 票并显示为另一个临时表。

表格1

表 2

结果

You can use a full join if the two table don't have the same number of rows:如果两个表的行数不同,则可以使用full join联接:

select coalesce(t1.categoryname, t2.categoryname) as categoryname,
       coalesce(t1.departmentname, t2.departmentname) as departmentname,
       coalesce(phonetickets, 0) + coalesce(ivrtickets, 0) as total_tickets
from table1 t1 full join
     table2 t2
     on t1.categoryname = t2.categoryname and
        t1.departmentname = t2.departmentname;

If the two tables have the same categories and departments, then inner join is fine.如果两个表有相同的类别和部门,那么inner join就可以了。

You can USE a UNION ALL and GROUP BY to get the result that you want您可以使用UNION ALLGROUP BY来获得您想要的结果

;WITH tckts as (
Select 
  CategoryName
  ,DepartmentName
  ,PhoneTickets [Tickets]
FROM Table1 t1
UNION ALL
Select 
  CategoryName
  ,DepartmentName
  ,IVRTickets [Tickets]
FROM Table2 t2
)
SELECT 
  CategoryName
  ,DepartmentName
  ,SUM(Tickets) [TotalTickets]
FROM tckts
GROUP BY CategoryName, DepartmentName

A better way to do the same would be to create a single table for both Phone Tickets and IVR Tickets and have a column, lets say [TicketType] which will have a value describing whether the ticket is a Phone Ticket or an IVR Ticket or any other Ticket types you have in the Future一个更好的方法是为电话票和 IVR 票创建一个表,并有一个列,比如 [TicketType],它将有一个值来描述票是电话票还是 IVR 票或任何您将来拥有的其他票证类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM