从sql server中的两个表的union中选择count

时间:2015-11-02 10:30:12

标签: sql-server count max union

我在SQL Server中的两个表之间有一个联合。联合表中的每个选择都包含一个计数。 我想收集结果,以便每个联合记录都包含两个计数器。 我的查询类似于以下内容:

SELECT ID,
       NAME,
       MAX(tableAcounter) AS counterA,
       MAX(tableBcounter) AS counterB
FROM ((SELECT ID,
              NAME,
              COUNT(*) OVER() AS tableAcounter
              0 AS tableBcounter
       FROM tableA
       GROUP BY ID,
                NAME)
      UNION ALL
     (SELECT ID,
             NAME,
             0 AS tableAcounter,
             COUNT(*) OVER() AS tableBCounter
      FROM tableB
      GROUP BY ID,
               NAME))
GROUP BY ID,
         NAME

我们说我在桌子A上有3条记录,在表格B上有5条记录。 我不明白为什么我会获得以下记录:

ID: 1
NAME: foo
counterA: 3
counterB: 0

ID: 5
NAME: baz
counterA: 0
counterB: 5

ID 21
NAME: bar
counterA: 3
counterB: 0

而不是:

ID: 1
NAME: foo
counterA: 3
counterB: 5

ID: 5
NAME: baz
counterA: 3
counterB: 5

ID 21
NAME: bar
counterA: 3
counterB: 5

0 个答案:

没有答案