SELECT COUNT(DISTINCT [name]) from several tables

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

    In case you have different amounts of columns per table, like:

    • table1 has 3 columns,
    • table2 has 2 columns,
    • table3 has 1 column

    And you want to count the amount of distinct values of different column names, what it was useful to me in AthenaSQL was to use CROSS JOIN since your output would be only one row, it would be just 1 combination:

    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
    

    Would return a table with one row and their counts:

    amt_name1 | amt_name2 | amt_name3 | amt_name4 | amt_name5 | amt_name6
        4123  |    675    |    564    |    2346   |   18667   |    74567
    

提交回复
热议问题