3

表格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:(需要帮助)

现在,前面的查询只获取了一张表的票和票数。我还需要在 table2 中计算同一张票的数量(因为两者都有相同的 tkt nos 集)。

我需要这样的结果:

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

表 1 和表 2 的票号相同,但计数不同

我如何得到如上图所示的结果?

4

3 回答 3

8

A simpler solution from a "statement point of view" (without COALESCE that maybe it's not so easy to understand).

Pay attention to the performances:

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

于 2013-08-27T13:34:50.410 回答
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;
于 2013-08-27T13:26:12.340 回答
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  
于 2016-10-30T06:03:40.573 回答