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

436
Views
¿Cómo calcular SUM para cada criterio en 1 campo en SQL?

Estoy de vuelta jajaja, estoy tratando de calcular lo siguiente:

averigüe cuántos usuarios tenían un saldo superior a £ 2000 al menos una vez en los últimos 30 días, por lo que debe ser crédito-débito para obtener el saldo de cada usuario.

adjunto la base de datos ingrese la descripción de la imagen aquí

He intentado lo siguiente, básicamente una autocombinación, pero faltan valores en el resultado.

 SELECT user_id, (credit_amount - debit_amount) AS balance FROM (SELECT A.user_id, A.type, B.type, A.amount AS debit_amount, B.amount AS credit_amount FROM public.transaction A, public.transaction B WHERE A.user_id = B.user_id AND a.type LIKE 'debit' AND b.type LIKE 'credit' AND A.created_at >= CURRENT_DATE - INTERVAL '30 days' AND A.created_at <= CURRENT_DATE) AS table_1 WHERE (credit_amount - debit_amount) > 2000 ;

Sin embargo, user_id 3 se está omitiendo debido a que no tiene crédito durante el intervalo de tiempo y se están perdiendo algunos valores... cualquier ayuda sería buena, gracias.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

averigüe cuántos usuarios tenían un saldo superior a £ 2000 al menos una vez en los últimos 30 días,

Puede usar funciones de ventana para calcular el saldo corriente de cada usuario durante el período. Luego, solo necesita contar los distintos usuarios cuyo saldo actual excedió el umbral:

 select count(distinct user_id) no_users from ( select user_id, sum(case when type = 'credit' then amount else -amount end) over(partition by user_id order by created_at) balance from transaction where created_at >= current_date - interval '30' day and created_at < current_date ) t where balance > 2000
over 4 years ago · Santiago Trujillo Report

0

Usar agregación condicional:

 select user_id, (sum(amount) filter (where type = 'credit') - coalesce(sum(amount) filter (where type = 'debit'), 0) ) from public.transaction t where t.created_at >= CURRENT_DATE - INTERVAL '30 days' and t.created_at < CURRENT_DATE group by user_id;
over 4 years ago · Santiago Trujillo Report

0

SELECT user_id, c.credit_amount - b.debit_amount AS balance FROM public.transaction a JOIN (SELECT user_id, type, amount AS debit_amount, FROM public.transaction where a.type LIKE 'debit') b on a.user_id = b.user_id JOIN (SELECT user_id, type, amount AS credit_amount FROM public.transaction where type LIKE 'credit') c on a.user_id = c.user_id WHERE a.created_at >= CURRENT_DATE - INTERVAL '30 days' AND a.created_at <= CURRENT_DATE) AS table_1 AND (c.credit_amount - b.debit_amount) > 2000 GROUP BY a.user_id;
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!