make a grouping select per year

0

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

asked by anonymous 31.01.2018 / 16:10

3 answers

3

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;
    
31.01.2018 / 16:12
1
  

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);

  

IfthedataCadastrofieldisoftypevarchar,youfirsthavetoconverttodateformatusingthe STR_TO_DATE , then you can use the YEAR function. YEAR(STR_TO_DATE(dataCadastro, "%Y-%m-%d"))

    
31.01.2018 / 16:59
0

If YEAR is in date format then you can use SUBSTRING from MySql

  

SELECT count (*) as total, SUBSTRING (year, 1,4)
  FROM cliente
  GROUP by SUBSTRING (year, 1.4)

    
31.01.2018 / 18:07