2

Para un problema necesito hacer una consulta que me devuelva 7 campos, los primeros tres se encuentran en la tabla "Contest", el cuarto y quinto son sumas agrupadas de dos columnas de la tabla "View_Stats" y el sexto y septimo igual son sumas agrupadas de la tabla "Submission_Stats".

Por la naturaleza del problema necesito una intrincada conexion que funciona perfecto hasta que agrego la quinta tabla, entonces las sumas dejan de funcionar.

Este es el codigo que me imprime las primeras dos sumas con resultados correctos.

SELECT Contests.contest_id, hacker_id, name, 
    SUM(total_submissions), 
    SUM(total_accepted_submissions)
    FROM 
    Contests 
    INNER JOIN Colleges ON Contests.contest_id = Colleges.contest_id
    INNER JOIN Challenges ON Colleges.college_id = Challenges.college_id
    INNER JOIN Submission_Stats ON Challenges.challenge_id = Submission_Stats.challenge_id
GROUP BY Contests.contest_id, hacker_id, name
ORDER BY Contests.contest_id;

Resultado:

845 579 Rose 1987 580

858 1053 Angela 703 160

883 1055 Frank 1121 319

Pero al agregar la quinta tabla que contiene los datos para las ultimas dos sumas las primeras dos sumas semodifican a pesar de que estos datos ni siquiera se encuentran en esta ultima tabla.

SELECT Contests.contest_id, hacker_id, name, 
    SUM(total_submissions), 
    SUM(total_accepted_submissions),
    SUM(total_views),
    SUM(total_unique_views)
    FROM 
    Contests 
    INNER JOIN Colleges ON Contests.contest_id = Colleges.contest_id
    INNER JOIN Challenges ON Colleges.college_id = Challenges.college_id
    INNER JOIN Submission_Stats ON Challenges.challenge_id = Submission_Stats.challenge_id
    INNER JOIN View_Stats ON Challenges.challenge_id = View_Stats.challenge_id
GROUP BY Contests.contest_id, hacker_id, name
ORDER BY Contests.contest_id;

Resultado

845 579 Rose 2566 841 2447 869

858 1053 Angela 1930 441 1464 511

883 1055 Frank 2689 734 1794 593

El problema completo lo pueden encontrar aqui https://www.hackerrank.com/challenges/interviews/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen

2
  • Seria interesante saber la relacion entre las tablas, y los datos de las mismas. Poner un link con el problema que estas tratando de resolver no es bueno, porque si desaparece la pregunta deja de tener sentido.
    – gbianchi
    el 24 abr. 2019 a las 2:05
  • Intentare poner lo mas claro posible las tablas y conexiones, gracias por el dato el 24 abr. 2019 a las 8:11

2 respuestas 2

1

Si las tablas Submission_Stats y View_Stats tienen varios registros para el mismo challenge_id, estás cogiendo todos los registros unificados de ambos. Ejemplo

Submission_Stats
1 - 10
1 - 20
View_Stats
1 - 100
1 - 200

Con tu consulta estás cogiendo
1 - 10 - 100
1 - 10 - 200
1 - 20 - 100
1 - 20 - 200

Y luego estás agrupando, lo que hace que en lugar de darte
1 - 30 - 300
te esté dando
1 - 60 - 600

Además, si tiene registros en una de las dos pero no en la otra, estás perdiendo esa línea al hacer el INNER JOIN. Hay que convertirlos en LEFT JOIN.

Lo que buscas es algo como esto:

SELECT a.contest_id, a.hacker_id, a.name,
    SUM(x.total_submissions),
    SUM(x.total_accepted_submissions),
    SUM(y.total_views),
    SUM(y.total_unique_views)
    FROM Contests a
        INNER JOIN Colleges b ON b.contest_id = a.contest_id
        INNER JOIN Challenges c ON c.college_id = b.college_id
        LEFT JOIN (SELECT challenge_id, SUM(total_submissions) AS total_submissions, SUM(total_accepted_submissions) AS total_accepted_submissions FROM Submission_Stats GROUP BY challenge_id) x ON x.challenge_id = c.challenge_id
        LEFT JOIN (SELECT challenge_id, SUM(total_views) AS total_views, SUM(total_unique_views) AS total_unique_views FROM View_Stats GROUP BY challenge_id) y ON y.challenge_id = c.challenge_id
    GROUP BY a.contest_id, a.hacker_id, a.name
    HAVING SUM(total_submissions) > 0
        OR SUM(total_accepted_submissions) > 0
        OR SUM(total_views) > 0
        OR SUM(total_unique_views) > 0
    ORDER BY a.contest_id;
1
  • Wow era exactamente eso, un poco complejo de deducir para un novato jaja. Gracias el 25 abr. 2019 a las 1:40
0

Lo que está ocurriendo es que, al hacer la operación join, habiendo más de un registro relacionado en la quinta tabla, te distorsiona el resultado del sum, pues aparecerán tantas filas como haya en esta tabla.

Lo que puedes hacer es calcular las sumas en un CTE o en una sub-consulta. Dado que no especificas el motor, te presento ambas. Yo en general prefiero el CTE por ser más legible, pero no está soportado en motores antiguos o desactualizados.

Haciendo un CTE, por ejemplo, podríamos tener:

with
Sub as (
select   challenge_id
       , sum(total_submissions) total_submissions
       , sum(total_accepted_submissions) total_accepted_submissions
  from Submission_Stats
 group by challenge_id
)
,
Vw as (
select   challenge_id
       , sum(total_views) total_views
       , sum(total_unique_views) total_unique_views
  from View_Stats
 group by challenge_id
)

SELECT   Contests.contest_id
       , hacker_id
       , name
       , Sub.total_submissions
       , Sub.total_accepted_submissions
       , Vw.total_views
       , Vw.total_unique_views
  FROM Contests
       INNER JOIN Colleges ON Contests.contest_id = Colleges.contest_id
       INNER JOIN Challenges ON Colleges.college_id = Challenges.college_id
       left join Sub ON Challenges.challenge_id = Sub.challenge_id
       left join Vw ON Challenges.challenge_id = Vw.challenge_id
 ORDER BY Contests.contest_id;

Haciendo sub-consultas, quedaría algo así:

SELECT   Contests.contest_id
       , hacker_id
       , name
       , (select sum(total_submissions)
            from Submission_Stats
           where Submission_Stats.Challenge_id = Challenges.challenge_id
         ) total_submissions
       , (select sum(total_accepted_submissions)
            from Submission_Stats
           where Submission_Stats.Challenge_id = Challenges.challenge_id
         ) total_accepted_submissions
       , (select sum(total_views)
            from View_Stats
           where View_Stats.Challenge_id = Challenges.challenge_id
         ) total_views
       , (select sum(total_unique_views)
            from View_Stats
           where View_Stats.Challenge_id = Challenges.challenge_id
         ) total_unique_views
  FROM Contests
       INNER JOIN Colleges ON Contests.contest_id = Colleges.contest_id
       INNER JOIN Challenges ON Colleges.college_id = Challenges.college_id
 ORDER BY Contests.contest_id;

Un saludo.

1
  • Tambien esto funciono, gracias,saludos! el 25 abr. 2019 a las 1:41

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.