SQL查询 - 从两个表中获取两列的计数

时间:2013-08-27 13:19:19

标签: sql sql-server sql-server-2008

表1:

TicketNumber    | Rules
---------------------------
PR123       | rule_123
PR123       | rule_234
PR123       | rule_456
PR999       | rule_abc
PR999       | rule_xyz

表2:

TicketNumber    | Rules
---------------------------
PR123       | rule_123
PR123       | rule_234
PR999       | rule_abc

注意:两个表都具有相同的结构:相同的列名但计数不同。

注意:两个表都有相同的TicketNumber值集

案例1: 如果我需要来自table1的每个故障单的故障单和规则计数,则查询为:

Select [TicketNo], COUNT([TicketNo]) AS Rules_Count from [Table1] group by TicketNo

这将以格式提供输出:

ticketNumber    | Rules_Count
---------------------------
PR123       | 3
PR999       | 9

案例2 :(需要帮助)

现在,上一个查询获取故障单和仅有1个表的故障单计数。我需要在table2中计算同一张票(因为两者都有相同的tkt nos)。

我需要这样的结果:

ticketNumber    | Count(ticketNumber) of table1 | Count(ticketNumber) of table2
---------------------------------------------------------------------------------
PR123       | 3                 | 2
PR999       | 2                 | 1

Table1和table2都具有相同的票数nos但计数不同

如何获得如上所示的结果?

3 个答案:

答案 0 :(得分:7)

从“声明的观点”(没有COALESCE的一个更简单的解决方案,可能它不是那么容易理解)。

注意表演:

Select T1.TicketNumber,T1.Rules_Count_1,T2.Rules_Count_2
FROM
(
  Select [TicketNumber], COUNT([TicketNumber]) AS Rules_Count_1 
  from [Table1] T1
  group by TicketNumber) T1
INNER JOIN
(
  Select [TicketNumber], COUNT([TicketNumber]) AS Rules_Count_2
  from [Table2] T2
  group by TicketNumber
 ) T2
on T1.TicketNumber = T2.TicketNumber

SQL Fiddle Demo

答案 1 :(得分:2)

您可以在聚合后使用full outer join执行此操作(如果您确实知道两个表具有相同的票证,则可以使用内部联接:

select coalesce(t1.TicketNo, t2.TicketNo) as TicketNo,
       coalesce(t1.Rules_Count, 0) as t1_Rules_Count,
       coalesce(t2.Rules_Count, 0) as t2_Rules_Count
from (Select [TicketNo], COUNT([TicketNo]) AS Rules_Count
      from [Table1]
      group by TicketNo
     ) t1 full outer join
     (Select [TicketNo], COUNT([TicketNo]) AS Rules_Count
      from [Table2]
      group by TicketNo
     ) t2
     on t1.TicketNo = t2.TicketNo;

答案 2 :(得分:0)

SELECT A.center,
       A.total_1st,
       B.total_2nd
FROM   (SELECT a.center,
               Count (a.dose1) AS Total_1st
        FROM   table_1 a
        GROUP  BY a.center) A
       INNER JOIN (SELECT b.center,
                          Count (b.dose2) AS Total_2nd
                   FROM   table_2 b
                   GROUP  BY b.center) B
               ON a.center = b.center
ORDER  BY A.center