简体   繁体   中英

SQL - Divide One Query by Another

I am trying to create a query which returns the workout percentage completion...

Workout Percentage Completion =

((Sum of LogEntries WHERE date = IN list of dates and WorkoutID =1 ) /

(Sum of all set numbers WHERE WorkoutID = 1)) x 100

Below is what I currently have, at the moment it is only returning the result of the first query. What should I change for the query to run correctly?

SELECT
  (
    (
     SELECT COUNT(LogEntriesID) 
     FROM LogEntriesTable 
     LEFT JOIN ExerciseWorkoutJunctionTable 
        ON ExerciseWorkoutJunctionTable.ExerciseWorkoutJunctionID =
           LogEntriesTable.JunctionID
     WHERE LogEntriesTable.date IN (
       "14-05-2020", "15-05-2020", "16-05-2020", "17-05-2020", 
       "18-05-2020", "19-05-2020", "20-05-2020"
       )
       AND ExerciseWorkoutJunctionTable.WorkoutID = 1
    ) / (
     SELECT sum(SetNumber) 
     FROM ExerciseWorkoutGoalsTable
     LEFT JOIN ExerciseWorkoutJunctionTable
         ON ExerciseWorkoutJunctionTable.ExerciseWorkoutJunctionID =
            ExerciseWorkoutGoalsTable.JunctionID 
     WHERE ExerciseWorkoutJunctionTable.WorkoutID = 1
    )
  )

Your first SELECT statement is doing an OUTER JOIN but then you have a WHERE clause that is selecting non-NULL values from the ExerciseWorkoutJunctionTable table, so I suspect you might as well be doing an INNER JOIN.

When you have two queries, try:

SET @sum = (SELECT SUM(SetNumber) etc ....);
SELECT (COUNT(LogEntriesID) * 100 / @sum) AS percentage
FROM etc.

If you are using MySQL >= 8.0 you should be able to use window functions like this which breakdown your query into more readable sections.

with entries as (
    SELECT COUNT(LogEntriesID) as log_entry_count
    FROM LogEntriesTable as l
    LEFT JOIN ExerciseWorkoutJunctionTable as e ON 
        e.ExerciseWorkoutJunctionID = l.JunctionID 
    WHERE l.date IN ("14-05-2020","15-05-2020","16-05-2020","17-05-2020","18-05-2020","19-05-2020","20-05-2020") 
        AND e.WorkoutID = 1
),
sets as (
    SELECT sum(SetNumber) as set_sum
    FROM ExerciseWorkoutGoalsTable as eg
    LEFT JOIN ExerciseWorkoutJunctionTable ej
        ON ej.ExerciseWorkoutJunctionID = eg.JunctionID 
    WHERE ej.WorkoutID = 1
)
select ((select log_entry_count from entries) / (select set_sum from sets)) * 100 as workout_completion_pct

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM