SQL Grouping by name, date and quantity per month

4

I am not able to group this resulting per month (FIELD "PP.PAPELETA_DATA"). Type the amount (count (PD.PessoaId) as Total) separated per month! Could someone give me a help? Use SQL SERVER 2012.

SELECT 
PE2.PessoaNome,
count(PD.PessoaId) as Total
FROM PAPELETA PP
INNER JOIN PESSOASDETALHE PD ON PP.PAPELETA_PESS = PD.PessoaId
INNER JOIN PESSOAS PE ON PD.AnalistaId = PE.PessoaId
INNER JOIN PESSOAS PE2 ON PP.PAPELETA_PESS = PE2.PessoaId
GROUP BY PE2.PessoaNome

    
asked by anonymous 14.02.2015 / 23:54

2 answers

2

You can use the built-in MONTH , datetime , smalldatetime , datetime / em>, datetime2 or datetimeoffset as stated in the function documentation. In conjunction with MONTH , you can also use CASE and SUM to check if the date is a specific month, if it is you add one more, otherwise disregard, something like this:

SELECT 
    PE2.PessoaNome,
    SUM(CASE WHEN (MONTH(PP.PAPELETA_DATA) = 1) THEN 1 ELSE 0 END) Qtd_Jan,
    SUM(CASE WHEN (MONTH(PP.PAPELETA_DATA) = 2) THEN 1 ELSE 0 END) Qtd_Fev,
    SUM(CASE WHEN (MONTH(PP.PAPELETA_DATA) = 3) THEN 1 ELSE 0 END) Qtd_Mar,
FROM 
    PAPELETA PP
    INNER JOIN PESSOASDETALHE PD ON PP.PAPELETA_PESS = PD.PessoaId
    INNER JOIN PESSOAS PE ON PD.AnalistaId = PE.PessoaId
    INNER JOIN PESSOAS PE2 ON PP.PAPELETA_PESS = PE2.PessoaId
GROUP BY 
    PE2.PessoaNome
  

Note: I do not have SQL SERVER to test at the moment, but the logic is this, if you have any problems, leave a comment on the response that I correct as soon as possible.

    
17.02.2015 / 14:49
1

Hello, Rafael,

You need to group by date as well.

Remember to delete the days of the PAPELETA_DATA date, otherwise you will have the data grouped by the days. This is why you use the MONTH and YEAR functions. It looks more or less like your query:

SELECT PE2.PessoaNome       
     , 'Qtd-' + CONVERT(CHAR(2), MONTH(PP.PAPELETA_DATA)) + '-' + CONVERT(CHAR(4),     YEAR(PP.PAPELETA_DATA)) AS Periodo
     , COUNT(PD.PessoaId) AS Total
  FROM PAPELETA            PP
 INNER JOIN PESSOASDETALHE PD ON PP.PAPELETA_PESS   = PD.PessoaId
 INNER JOIN PESSOAS        PE ON PD.AnalistaId      = PE.PessoaId
 INNER JOIN PESSOAS       PE2 ON PP.PAPELETA_PESS   = PE2.PessoaId
 GROUP BY PE2.PessoaNome
        , MONTH(PP.PAPELETA_DATA)
        , YEAR(PP.PAPELETA_DATA)
    
20.02.2015 / 12:40