SELECT COUNT(DISTINCT [name]) from several tables

前端 未结 4 1335
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-06 08:28

I can perform the following SQL Server selection of distinct (or non-repeating names) from a column in one table like so:

SELECT COUNT(DISTINCT [Name]) FROM [MyT         


        
4条回答
  •  失恋的感觉
    2021-02-06 09:20

    Here's another way:

    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
    

提交回复
热议问题