sql >> Base de Datos >  >> RDS >> PostgreSQL

Pivote en Postgresql con marcas VERDADERO/FALSO

Experimenté un poco y esto es lo que se me ocurrió.

# Reading the data into a table

SELECT * INTO crosstab_test FROM 
(VALUES (20180101,'001','Dog','Asthma','Mucus'),
(20180101,'001','Dog','Asthma','Noisy'),
(20180101,'001','Dog','Asthma','Respiratory'),
(20180102,'002','Cat','Osteoarthritis','Locomotor'),
(20180102,'002','Cat','Osteoarthritis','Limp'),
(20180131, '003', 'Bird', 'Avian Pox','Itchy')) as a (date, id, species, illness, tag);

SELECT DISTINCT date, id, species, illness, mucus, noisy, locomotor, respiratory,  limp, itchy 
FROM 
(SELECT "date", id, species, illness
FROM crosstab_test) a
INNER JOIN             
(SELECT * FROM crosstab(
'SELECT id, tag, ''TRUE'' FROM crosstab_test ORDER BY 1,2,3',
'SELECT DISTINCT tag FROM crosstab_test ORDER BY 1')
as tabelle (id text, Itchy text, Limp text, Locomotor text, Mucus text, Noisy text, Respiratory text)) b
USING(id)
ORDER BY 1;


   date   | id  | species |    illness     | mucus | noisy | locomotor | respiratory | limp | itchy
----------+-----+---------+----------------+-------+-------+-----------+-------------+------+-------
 20180101 | 001 | Dog     | Asthma         | TRUE  | TRUE  |           | TRUE        |      |
 20180102 | 002 | Cat     | Osteoarthritis |       |       | TRUE      |             | TRUE |
 20180131 | 003 | Bird    | Avian Pox      |       |       |           |             |      | TRUE
(3 Zeilen)

Si no le importa el orden de las columnas, puede hacer SELECT DISTINCT * ...

Reemplazando el NULL s con FALSE probablemente va a ser un poco difícil teniendo en cuenta las 350 etiquetas que dices que tienes. Así que sugiero dejarlos lejos. Si los quiere, puede hacer SELECT DISTINCT date, id, species, illness, COALESCE(mucus, 'FALSE'), COALESCE(noisy, 'FALSE'),...

Sin embargo, la píldora amarga que tendrá que tragar es especificar las 350 etiquetas como columna con el tipo text en as the tabelle (id text, Itchy text, Limp text, Locomotor text, Mucus text, Noisy text, Respiratory text) -parte de la declaración de tabulación cruzada. Asegúrese de ponerlos en el orden correcto según lo determinado por 'SELECT DISTINCT tag FROM crosstab_test ORDER BY 1' también en la tabla de referencias cruzadas.

Espero que eso sea lo que estabas buscando.