计算2个不同的表

时间:2015-07-31 08:17:06

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

我想为2个不同的表创建一个COUNT,我尝试下一个代码,但它只为gal表提供了结果。我需要修改以获得多行如何在gal和TLP中重复

代码是:

SELECT name, GIVEN_NAME, mail, COUNT(*) AS DUPS 
FROM   Glob 
WHERE  ( NOT EXISTS (SELECT email1 
                     FROM   TLP
                     WHERE  GLOB.mail = TLP.email1 ) 
         AND GLOB.mail IS NOT NULL ) 
        AND ( NOT EXISTS (SELECT LASTNAME 
                         FROM   TLP
                         WHERE  GLOB.NAME = TLP.LASTNAME ) 
             AND GLOB.NAME IS NOT NULL )
        AND
              (NOT EXISTS (SELECT FIRSTNAME 
                     FROM   TLP 
                     WHERE  GLOB.GIVEN_NAME = TLP.FIRSTNAME ) 
         AND GLOB.NAME IS NOT NULL ) 
         AND GLOB.COUNTRY='Germany'
         GROUP BY NAME, GIVEN_NAME, MAIL
         HAVING (COUNT(*)>1);

1 个答案:

答案 0 :(得分:0)

根据您的查询,不太确定您要在此处执行的操作。如果您只是在寻找快速而脏的行计数,可以将其包装在这样的公用表表达式中。

;with cte_mycount AS(
SELECT NAME, 
       given_name, 
       mail 
FROM   gal 
WHERE  ( NOT EXISTS (SELECT email1 
                     FROM   tcpd_personel 
                     WHERE  gal.mail = tcpd_personel.email1) 
         AND gal.mail IS NOT NULL ) 
       AND ( NOT EXISTS (SELECT lastname 
                         FROM   tcpd_personel 
                         WHERE  gal.NAME = tcpd_personel.lastname) 
             AND gal.NAME IS NOT NULL ) 
       AND ( NOT EXISTS (SELECT firstname 
                         FROM   tcpd_personel 
                         WHERE  gal.given_name = tcpd_personel.firstname) 
             AND gal.NAME IS NOT NULL ) 
       AND gal.country = 'Germany' 
GROUP  BY NAME, 
          given_name, 
          mail 
HAVING ( Count(*) > 1 ))
SELECT COUNT(*) FROM cte_mycount