Pergunta

I have a table containing transaction details which I am importing from several vendor-provided daily reports.. I want to be sure that I am not skipping any of the files (one file per day) as I do this process..

So I wanted to query the database to find the number of distinct dates it found in the result set.

At first I tried to execute:

SELECT COUNT(t.*) FROM (SELECT DISTINCT `Date of Survey`  from cc.voc_detail_old) t;

But that generates the error "* SQL Error (1064): You have an error in your SQL syntax;..."

Changing it to SELECT Count(*)... resolves the error and the query functions as expected. Why is it not permissible to use the alias of the derived table in the Count() function, but the derived table's alias is required per syntax?

Foi útil?

Solução

In MariaDB, the COUNT() function expects an expression (that is to say, a single value). For each row where the expression is not NULL, that row will be counted. With DISTINCT, as you note, it will only count each distinct non-NULL value once.

COUNT(*) is a special case, returning the number of rows in your result set.

COUNT(t.*) would only work if there's only one column in table t.

Per the OP's testing and my own, COUNT(t.*) does not work even if the table only has one column. See this dbfiddle.uk link to confirm this for yourself.

(Note: You can also see that some other versions of SQL can handle this; if you switch the DB engine to a version of Postgres, the last statement runs successfully, instead of generating an error).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a dba.stackexchange
scroll top