I have a client field in it I need to make a count of how many customers were registered during the years 2016, 2017 and 2018.
I was doing 3 select, and in each one I made a where dataCadastro > = 2016-01-01 and dataCadastro
I have a client field in it I need to make a count of how many customers were registered during the years 2016, 2017 and 2018.
I was doing 3 select, and in each one I made a where dataCadastro > = 2016-01-01 and dataCadastro
Follows:
SELECT COUNT(*) AS QTD_CLIENTES_CADASTRADOS, EXTRACT(YEAR FROM DATACADASTRO) AS ANO
FROM TABELA
WHERE EXTRACT(YEAR FROM DATACADASTRO) IN (2016, 2017, 2018)
GROUP BY EXTRACT(YEAR FROM DATACADASTRO);
Explanation:
When using the EXTRACT (YEAR FROM DATE)
function you will extract the day / month / year of a determining% field of% of your database, with this function you can do conditional, use in timestamp
, add in order by
between other features.
I used SELECT
to avoid adding 3 in
(which would refer to each year), thus avoiding the and
big without need.
Edited
There is another way to do this SQL
avoiding so many SQL
:
SELECT COUNT(S.QTD) AS CLIENTES_CADASTRADOS, S.ANO
FROM (SELECT 1 AS QTD, EXTRACT(YEAR FROM DATACADASTRO) AS ANO
FROM TABELA) AS S
WHERE S.ANO IN (2016, 2017, 2018);
GROUP BY S.ANO;
If the dates are in date or datetime fields, you can use YEAR
YEAR (date) - Returns an integer that represents the year of the specified date.
SELECT COUNT(coluna), YEAR(dataCadastro) FROM tabela GROUP BY YEAR(dataCadastro);
Example:
Table
ResultSELECTCOUNT(id),YEAR(dataCadastro)FROMtabela2GROUPBYYEAR(dataCadastro);
Ifthe
dataCadastro
fieldisoftypevarchar,youfirsthavetoconverttodateformatusingthe STR_TO_DATE , then you can use the YEAR function.YEAR(STR_TO_DATE(dataCadastro, "%Y-%m-%d"))