Turning rows into columns

0

I would like to convert some table values into columns. The structure of the table would be basically this:

| id | idUnidade | mesCompetencia | valor |
|----|-----------|----------------|-------|
| 1  | 237       | 2017-05-01     | 35    |
| 2  | 237       | 2017-06-01     | 45    |
|

My select searches the data between two dates, simplifying it would be two months, and I would like the values to be assigned to the column "valueCompetence" and "previousvalue" on a single line grouped by unit code.

Current SQL

SELECT 
    idUnidade,
    MONTH(MIN(mesCompetencia)) as mesAnterior,
    MONTH(MAX(mesCompetencia)) as mesAtual,

    #---------TENTATIVAS SEM SUCESSO---------
    #[Err] 1111 - Invalid use of group function
    SUM(CASE MONTH(mesCompetencia) WHEN MONTH(MIN(mesCompetencia)) THEN valor END) as valorAnterior
    #[Err] 1111 - Invalid use of group function
    SUM(CASE WHEN MONTH(mesCompetencia) = MONTH(MIN(mesCompetencia)) THEN valor END) as valorAnterior
    #[Err] 1054 - Unknown column 'mesAnterior' in 'field list'
    SUM(CASE MONTH(mesCompetencia) WHEN mesAnterior THEN valor END) as valorAnterior
    #[Err] 1111 - Invalid use of group function
    SUM( if (MIN(mesCompetencia) = mesCompetencia, valor, 0)) as valorAnterior
    #[Err] 1111 - Invalid use of group function
    SUM(CASE WHEN MIN(mesCompetencia) = mesCompetencia THEN valor ELSE 0 END) as valorAnterior
    #[Err] 1111 - Invalid use of group function    
    SUM(CASE MIN(mesCompetencia) WHEN mesCompetencia THEN valor ELSE 0 END) as valorAnterior

FROM Tabela 
WHERE ....... mesCompetencia BETWEEN 'X' AND 'Y' .....
GROUP BY idUnidade

With this SQL (ignoring unsuccessful attempts) I have the following result:

| idUnidade | mesAtual | mesAnterior |
|-----------|----------------|-------------|
| 237       | 06             | 05
|

But the result I would like is:

| idUnidade | mesAtual | mesAnterior | valorCompetencia | valorAnterior |
|-----------|----------|-------------|------------------|---------------|
| 237       | 06       | 05          | 45               |  35       
|
|

The attempts I made are listed in the SQL that is up there, could anyone help me group those values together?

OBS: If there is a solution without subselects it would be interesting as there are many other clauses in the where they were hidden.

    
asked by anonymous 17.08.2017 / 20:16

0 answers