比较两个表中的值计数

时间:2014-07-24 14:28:30

标签: sql sql-server-2008

如果两个表之间的值出现次数存在差异,我想强调两个表。基本上,表1可以包含4行,其中一列中包含单词“Ball”,表2中也包含4行,其中一列中包含单词ball。这将被忽略。但是,在表1中,球有4个实例,在表2中有6个实例,我希望输出类似于:

"Column Name"  "Table 1" "Table 2"  
  Ball             4          6

如何做到这一点?

2 个答案:

答案 0 :(得分:4)

;WITH CTE1 AS
(
   SELECT ColName,
          COUNT(ColName) AS NameCount
   FROM   Table1
   GROUP BY ColName
),CTE2 AS
(
   SELECT ColName,
          COUNT(ColName) AS NameCount
   FROM   Table2
   GROUP BY ColName
)
SELECT * 
FROM   CTE1 C1
       FULL OUTER JOIN CTE2 C2
       ON C1.ColName = C2.ColName
WHERE  C1.NameCount <> C2.NameCount

答案 1 :(得分:1)

此替代方案可以正确处理值在一个表中但不在另一个表中的情况。执行计划将类似于CTE版本,例如jyparask的回答。

SELECT
    COALESCE(t1.ColumnName, t2.ColumnName) AS [Column Name],
    COALESCE(t1.Occurrences, 0) AS [Table 1],
    COALESCE(t2.Occurrences, 0) AS [Table 2]
FROM (
    SELECT
        ColumnName,
        COUNT(ColumnName) AS Occurrences
    FROM
        Table1
    GROUP BY
        ColumnName
) t1
FULL OUTER JOIN (
    SELECT
        ColumnName,
        COUNT(ColumnName) AS Occurrences
    FROM
        Table2
    GROUP BY
        ColumnName
) t2
ON
    t1.ColumnName = t2.ColumnName
WHERE
    COALESCE(t1.Occurrences, 0) <> COALESCE(t2.Occurrences, 0)