Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
Cómo fusionar datos en una línea

Tengo datos en una base de datos PostgreSQL en el siguiente formato:

 unique_key category date_period value

Así por ejemplo.

 agriculture_all agriculture 2021 15 agriculture_partial agriculture 2021 10 science_all science 2021 83 science_partial science 2021 32

La consulta que quiero ejecutar es GROUP BY según la category y el date_period , pero luego mostrar los valores uno al lado del otro.

 **[query here]** output: category date_period all partial agriculture 2021 15 10 science 2021 83 32

Se siente como una solicitud realmente simple, pero estoy luchando para que funcione correctamente en SQL. Cualquier consejo apreciado.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

En PostgreSQL puede usar una consulta simple usando sum con filter :

 select category, sum(value) filter (where unique_key like '%_all') all, sum(value) filter (where unique_key like '%_partial') partial from tbl group by category;

Violín de filtro de suma de PostgreSQL

Para evitar valores null , se puede aplicar la función coalesce :

 select category, coalesce(sum(value) filter (where unique_key like '%_all'), 0) all, coalesce(sum(value) filter (where unique_key like '%_partial'), 0) partial from tbl group by category;

Filtro coalescente de PostgreSQL

over 4 years ago · Santiago Trujillo Report

0

Podrías usar una expresión de tabla común...

 with partial as (select category, date_period, value from t1 where unique_key ilike '%partial%' ) select a.category, a.date_period, a.value as all, coalesce(p.value, 0) as partial from t1 a left join partial p on p.category = a.category and p.date_period = a.date_period where a.unique_key ilike '%all%'

db-violín aquí

over 4 years ago · Santiago Trujillo Report

0

Un poco de agregación condicional hará el truco.

 SELECT t.category , t.date_period , SUM(CASE WHEN t.unique_key LIKE '%\_all' THEN t.value ELSE 0 END) AS "all" , SUM(CASE WHEN t.unique_key LIKE '%\_partial' THEN t.value ELSE 0 END) AS "partial" FROM your_table t GROUP BY t.category, t.date_period ORDER BY t.category, t.date_period
categoría | fecha_periodo | todos | parcial
:----------- | ----------: | --: | ------:
agricultura | 2021 | 15 | 10
ciencia | 2021 | 83 | 32

db<>violín aquí

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!