Reputation: 1675
I need to group multiple select statements into a single query and into multiple columns
I have already tried using UNION but it causes one of my selects to go missing (probably misusing it)
SELECT COUNT(*) AS EMERGENCIA FROM Incidentes WHERE Prioridad_Real = 'Emergencia' AND Estado = 'Resuelto a Tiempo'
AND Fecha_Asigna >= '2013-08-22 13:30:00.000' and Fecha_Resul <= '2013-08-23 11:16:00.000'
SELECT COUNT(*) AS ALTA FROM Incidentes WHERE Prioridad_Real = 'Alta' AND Estado = 'Resuelto a Tiempo'
AND Fecha_Asigna >= '2013-08-22 13:30:00.000' and Fecha_Resul <= '2013-08-23 11:16:00.000'
SELECT COUNT(*) AS MEDIA FROM Incidentes WHERE Prioridad_Real = 'Media' AND Estado = 'Resuelto a Tiempo'
AND Fecha_Asigna >= '2013-08-22 13:30:00.000' and Fecha_Resul <= '2013-08-23 11:16:00.000'
SELECT COUNT(*) AS BAJA FROM Incidentes WHERE Prioridad_Real = 'Baja' AND Estado = 'Resuelto a Tiempo'
AND Fecha_Asigna >= '2013-08-22 13:30:00.000' and Fecha_Resul <= '2013-08-23 11:16:00.000'
Expected Result:
Upvotes: 2
Views: 151
Reputation: 37313
Try using the following query:
SELECT SUM(CASE WHEN Prioridad_Real = 'Emergencia' THEN 1 ELSE 0 END) as EMERGENCIA,
SUM(CASE WHEN Prioridad_Real = 'Alta' THEN 1 ELSE 0 END) as ALTA,
SUM(CASE WHEN Prioridad_Real = 'Media' THEN 1 ELSE 0 END) as MEDIA,
SUM(CASE WHEN Prioridad_Real = 'Baja' THEN 1 ELSE 0 END) as BAJA
FROM Incidentes WHERE Estado = 'Resuelto a Tiempo'
AND Fecha_Asigna >= '2013-08-22 13:30:00.000' and Fecha_Resul <= '2013-08-23 11:16:00.000'
Upvotes: 6