SELECT COUNT(DISTINCT [name]) from several tables

前端 未结 4 1336
爱一瞬间的悲伤
爱一瞬间的悲伤 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:07

    After the clarification, use:

      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
    

    If I understand correctly, use:

      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 will remove duplicates; UNION ALL will not, and is faster for it.

提交回复
热议问题