1

我有下表:

 CodeName    cnt             cnt
CodeNAmeA   1111            2222
CodeNAmeB   3333            4444
CodeNAmeC   5555            6666

该表是以下查询的结果:

(select a.CodeName, a.cnt, b.cnt from

  (select tableA.CodeName, count(*) cnt
   from aaaa..AAAA tableA inner join bbbb..BBBB tableB 
   on tableA.CodeName = tableB.CodeName
   where XXXXXXX
   group by tableA.CodeName) a

   JOIN

  (select tableA.CodeName, count(*) cnt
   from aaaa..AAAA tableA inner join bbbb..BBBB tableB 
   on tableA.CodeName = tableB.CodeName
   where XXXXXXX
   group by tableA.CodeName,tableA.INAMALOCK) b

ON a.CodeName = b.CodeName) 

我有另一个这样的表:

 CodeName        RealName
CodeNAmeA       RealNameA
CodeNAmeB       RealNameB
CodeNAmeC       RealNAmeC

此表是简单选择查询的结果

select CodeName
from TableCodeReal

我想要做的是显示以下内容:

 RealName    cnt     cnt
RealNameA   1111    2222
RealNameB   3333    4444
RealNameC   5555    6666

问题来了,我在aaaa..AAAA 或bbbb..BBBB 中没有真实姓名,如何获取第一个查询的结果并进行替换?非常感谢,我对如何在第一个查询中集成第二个表感到非常困惑。

4

2 回答 2

2

我相信这是你需要的。使您的主查询成为子查询并加入您的第二个表的CodeName值。然后RealName从您的第二个表中选择 ,以及您的cnt值(我已将其别名为acntbcnt)。

SELECT T.RealName, Q.acnt, Q.bcnt
FROM
(select a.CodeName, a.cnt as acnt, b.cnt as bcnt from

  (select tableA.CodeName, count(*) cnt
   from aaaa..AAAA tableA inner join bbbb..BBBB tableB 
   on tableA.CodeName = tableB.CodeName
   where XXXXXXX
   group by tableA.CodeName) a

   JOIN

  (select tableA.CodeName, count(*) cnt
   from aaaa..AAAA tableA inner join bbbb..BBBB tableB 
   on tableA.CodeName = tableB.CodeName
   where XXXXXXX
   group by tableA.CodeName,tableA.INAMALOCK) b

ON a.CodeName = b.CodeName) Q
INNER JOIN TableCodeReal T ON Q.CodeName = T.CodeName
于 2012-08-10T09:56:03.937 回答
0

您可以将第一个记录集视为虚拟表。将记录集加入到您的第二张表中,您可以获得所需的结果。

select rt.RealName, vt.cnta, vt.cntb
from TableCodeReal rt
inner join 
(select a.CodeName, a.cnt as cnta, b.cnt as cntb from

  (select tableA.CodeName, count(*) cnt
   from aaaa..AAAA tableA inner join bbbb..BBBB tableB 
   on tableA.CodeName = tableB.CodeName
   where XXXXXXX
   group by tableA.CodeName) a

   JOIN

  (select tableA.CodeName, count(*) cnt
   from aaaa..AAAA tableA inner join bbbb..BBBB tableB 
   on tableA.CodeName = tableB.CodeName
   where XXXXXXX
   group by tableA.CodeName,tableA.INAMALOCK) b

ON a.CodeName = b.CodeName) vt on vt.CodeName = rt.CodeName
于 2012-08-10T09:59:35.933 回答