Skip to content
Advertisement

SQL: Return Aggregated Results based on some conditions

I need help with making a conclusion in SQL Server based on some column’s values, like status aggregation sort of. As an example, below is a table containing server tasks and their status.

If I want to return the aggregated status of each server here are the rules:

  • if all the server tasks are at status ‘SUBMITTED’, then the aggregated server status is ‘AWAITING’
  • if all tasks are at status ‘COMPLETED’ – the aggregated status is ‘DONE’
  • if the above cases are not met, the aggregated server status is ‘IN PROGRESS’

Example Table: Tasks

Server Task_Status Task
Server 1 RUNNING 1-1
Server 1 COMPLETED 1-2
Server 1 SUBMITTED 1-3
Server 2 COMPLETED 2-1
Server 2 COMPLETED 2-2
Server 3 SUBMITTED 3-1
Server 3 SUBMITTED 3-2

Example Query Result:

Server Completion
Server 1 IN PROGRESS
Server 2 DONE
Server 3 AWAITING

Advertisement

Answer

You could use this:

Tested in sqlfiddle

enter image description here

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