I have a SQL query that returns the following result:
Inquiry
+--------------------------------------------------------------------------+
| CONJUNTO | TIPO | FILHO | PAI | TIPO_CONTEUDO | TIPO_DESCRICAO |
+-------------|-------|--------|--------|-----------------|----------------+
| 8005 | 150 | 40 | NULL | 1 | ORDEM |
| 8005 | 150 | 41 | NULL | 2 | ORDEM |
| 8005 | 150 | 42 | NULL | 3 | ORDEM |
| 8005 | 201 | 43 | 40 | 2005 | ANO |
| 8005 | 202 | 44 | 40 | 10 | MES |
| 8005 | 203 | 45 | 40 | 101010 | NUMERO |
| 8005 | 204 | 46 | 40 | ST 1 | SETOR |
| 8005 | 205 | 47 | 40 | TESTE 1 | TIPO |
| 8005 | 201 | 48 | 41 | 2006 | ANO |
| 8005 | 202 | 49 | 41 | 11 | MES |
| 8005 | 203 | 50 | 41 | 202020 | NUMERO |
| 8005 | 204 | 51 | 41 | ST 2 | SETOR |
| 8005 | 205 | 52 | 41 | TESTE 2 | TIPO |
| 8005 | 201 | 53 | 42 | 2007 | ANO |
| 8005 | 202 | 54 | 42 | 12 | MES |
| 8005 | 203 | 55 | 42 | 303030 | NUMERO |
| 8005 | 204 | 56 | 42 | ST 3 | SETOR |
| 8005 | 205 | 57 | 42 | TESTE 3 | TIPO |
+--------------------------------------------------------------------------+
But I want some rows depending on the rule that I will explain below is returned as a column.
Result
+-------------------------------------------------------------------------------+
| CONJUNTO | TIPO_CONTEUDO | ANO | MÊS | NUMERO | SETOR | TIPO |
+-------------|---------------|--------|-------|----------|-----------|---------+
| 8005 | 1 | 2005 | 10 | 101010 | ST 1 | TESTE 1 |
| 8005 | 2 | 2006 | 11 | 202020 | ST 2 | TESTE 2 |
| 8005 | 3 | 2007 | 12 | 303030 | ST 3 | TESTE 3 |
+-------------------------------------------------------------------------------+
Description
- Select is filtered by SET (in case 8005).
- If the record has the field PAI equal to NULL it becomes a new record related to your SON along with the content of TIPO_CONTEUDO (ORDER).
- If the record has the PAI field other than NULL it must be linked to the respective PAI.
- The TYPE column is the ID of the TYPE_DESCRIPTION (TYPE_DESCRIPTION was added by me because it does not have the original table).
I'm sorry if you do not understand the rules, but in short, I'll link the SONS to the FATHER.