SQL count(*) and distinct

前端 未结 9 2028
野趣味
野趣味 2021-02-12 11:25

Why can\'t we use count(distinct *) in SQL? As in to count all distinct rows?

相关标签:
9条回答
  • 2021-02-12 12:03

    You can select all the columns in your table and group by...

    SELECT column1, column2, column3, count(*)
    FROM someTable
    GROUP BY column1, column2, column3
    
    0 讨论(0)
  • 2021-02-12 12:07
    select count(*) from (select distinct * from MyTable) as T
    

    Although I strongly suggest that you re-think any queries that use DISTINCT. In a large percentage of cases, GROUP BY is more appropriate (and faster).

    EDIT: Having read the question comments, I should point out that you should never ask the DBMS to do more work than actually needs doing to get a result. If you know in advance that there will not be any duplicated rows in a table, then don't use DISTINCT.

    0 讨论(0)
  • 2021-02-12 12:10

    COUNT(*) is the number of rows matching a query.

    A row contains unique information such as rowid. All rows are by definition distinct.

    You must count the distinct instances of values in some field instead.

    0 讨论(0)
提交回复
热议问题