从几个表中选择COUNT(DISTINCT [name])

时间:2011-07-15 19:19:59

标签: sql sql-server select count distinct

我可以从一个表中的列执行以下SQL Server选择的不同(或非重复名称),如下所示:

SELECT COUNT(DISTINCT [Name]) FROM [MyTable]

但是,如果我有多个表(所有这些表都包含名为[Name]的名称字段),我需要知道两个或多个表中非重复名称的数量。

如果我运行这样的事情:

SELECT COUNT(DISTINCT [Name]) FROM [MyTable1], [MyTable2], [MyTable3]

我收到错误,“不明确的列名称'名称'”。

PS。所有三个表[MyTable1],[MyTable2],[MyTable3]都是之前选择的产物。

4 个答案:

答案 0 :(得分:17)

澄清后,使用:

  SELECT x.name, COUNT(x.[name])
    FROM (SELECT [name]
            FROM [MyTable]
          UNION ALL
          SELECT [name]
            FROM [MyTable2]
          UNION ALL
          SELECT [name]
            FROM [MyTable3]) x
GROUP BY x.name

如果我理解正确,请使用:

  SELECT x.name, COUNT(DISTINCT x.[name])
    FROM (SELECT [name]
            FROM [MyTable]
          UNION ALL
          SELECT [name]
            FROM [MyTable2]
          UNION ALL
          SELECT [name]
            FROM [MyTable3]) x
GROUP BY x.name

UNION将删除重复项; UNION ALL不会,而且速度更快。

答案 1 :(得分:5)

编辑:看到最近的评论后不得不改变。

这会给你你想要的吗?这会在合并所有表格中的行后为每个人提供一个计数。

SELECT [NAME], COUNT(*) as TheCount
FROM
    (
     SELECT [Name] FROM [MyTable1]
     UNION ALL
     SELECT [Name] FROM [MyTable2]
     UNION ALL
     SELECT [Name] FROM [MyTable3]
     ) AS [TheNames]
GROUP BY [NAME]

答案 2 :(得分:1)

这是另一种方式:

SELECT x.name, SUM(x.cnt)
FROM ( SELECT [name], COUNT(*) AS cnt
       FROM [MyTable]
       GROUP BY [name]
     UNION ALL
       SELECT [name], COUNT(*) AS cnt
       FROM [MyTable2]
       GROUP BY [name]
     UNION ALL
       SELECT [name], COUNT(*) AS cnt
       FROM [MyTable3]
       GROUP BY [name]
     ) AS x
GROUP BY x.name

答案 3 :(得分:0)

如果每个表的列数不同,例如:

  • 表1有3列,
  • table2有2列,
  • 表3有1列

您想计算不同列名的不同值的数量,在 AthenaSQL 中,对我有用的是使用computed: { brandImg() { let brandImg = ''; let thisBrand = this.$store.state.ui.theme.brand; switch (thisBrand) { case 'brandOne': return '/img/iconOne.png'; case 'brandTwo': return '/img/iconTwo.png'; case 'brandThree': return '/img/iconThree.png'; default: console.warn('not configured`); break; } } } ,因为您的输出将只有一行,这将是1种组合:

CROSS JOIN

将返回具有一行及其计数的表:

SELECT * FROM (
SELECT COUNT(DISTINCT name1) as amt_name1,
       COUNT(DISTINCT name2) as amt_name2,
       COUNT(DISTINCT name3) as amt_name3,
FROM table1 ) t1
CROSS JOIN
(SELECT COUNT(DISTINCT name4) as amt_name4,
        COUNT(DISTINCT name5) as amt_name5,
        MAX(t3.amt_name6) as amt_name6
 FROM table2
 CROSS JOIN
 (SELECT COUNT(DISTINCT name6) as amt_name6
  FROM table3) t3) t2