Skip to content
Advertisement

Iterate through SQL result set adding subquery results to result set

I have a table [Robots] containing Robot IDs, and a [TestResults] table which has a FK to [Robots] of [RobotId]

What I am aiming to get is a result set of each robotID in the [Robots] table and for each ID a total of all entries in the [TestResults] of Status ‘Active’, ‘Failed’ and total of all status, I have been stuck on the approach for this.

eg:

I need a method to iterate through the IDs and perform these queries as below

Advertisement

Answer

Just join and conditionally sum e.g.

Typically if you find yourself considering loops in SQL you’ve taken a wrong turn. Its a set based language so needs to be approached as such.

Note the left join just in case a robot has no test results, it will still show in the list. If this isn’t the desired behaviour, change it to an inner join.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement