Turning rows into columns

Asked

Viewed 212 times

0

I would like to turn 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 would be two months, and would like the values to be assigned to the column "valueCompetencia" and "valueAnterior" in a single row grouped by the unit code.

SQL current

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’d 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 someone help me group these values?

OBS: If there is a solution without subselects it would be interesting as there are many other clavicles in Where that have been hidden.

  • The quickest way I could think of here would be to do a subselect.. for example select idUnidade, (select value from Table Where mes=MAX(mesCompetencia)) the valueCompetencia

  • @Lucas It would be a possibility, but it is from that situation that wanted to escape because of the Where clauses that would have to be included in this sub-select (I made an Obs at the end of the question); So far I have agreed the situation through programming... Thank you for your attention :)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.