1

Buen día

Tengo la siguiente tabla en MySQL:

id     |    pais    |  categoria
193    |     BR     |     A
188    |     BR     |     A
133    |     BR     |     B
145    |     BR     |     C
124    |     CA     |     A
165    |     CA     |     B
113    |     CA     |     B
177    |     CA     |     C
197    |     MX     |     A
213    |     MX     |     B
208    |     MX     |     C
222    |     MX     |     C

Quiero obtener el total de categoría por cada país en diferente columna, es decir:

categoria  |  totalBR  |  totalCA  |  totalMX
    A      |    2      |    1      |    1
    B      |    1      |    2      |    1
    C      |    1      |    1      |    2

Se me ocurre crear una tabla temporal para el total por país y categoría pero creo que no seria tan buena idea ya que tendría que crear 9 tablas temporales y después hacerles un union all

UPDATE

La 1er tabla la obtengo de una consulta SQL y como no pude obtener el total de diferentes columnas de la 1er tabla, modifique mi consulta SQL obteniendo la siguiente tabla:

  |      id     |    pais    |  categoriaBR  | categoriaCA  | categoriaMX  |
  |      193    |     BR     |     A         |     null     |    null      |
  |      188    |     BR     |     A         |     null     |    null      |
  |      133    |     BR     |     B         |     null     |    null      |
  |      145    |     BR     |     C         |     null     |    null      |
  |      124    |     CA     |    null       |       A      |    null      |
  |      165    |     CA     |    null       |       B      |    null      |
  |      113    |     CA     |    null       |       B      |    null      |
  |      177    |     CA     |    null       |       C      |    null      |
  |      197    |     MX     |    null       |     null     |      A       |
  |      213    |     MX     |    null       |     null     |      B       |
  |      208    |     MX     |    null       |     null     |      C       |
  |      222    |     MX     |    null       |     null     |      C       |

y cree 9 tablas temporales

#------------------------------------------------categoriasBR------------------------------------------------
DROP temporary table IF EXISTS categoriaBR1;
CREATE TEMPORARY TABLE IF NOT EXISTS categoriaBR1 AS ( 
    SELECT 1 as id, ifnull(sum(case when categoriaBR = 'A' then 1 else 0 end),0) as 'Total'
        FROM tabla
);

DROP temporary table IF EXISTS categoriaBR2;
CREATE TEMPORARY TABLE IF NOT EXISTS categoriaBR2 AS ( 
    SELECT 2 as id, ifnull(sum(case when categoriaBR = 'B' then 1 else 0 end),0) as 'Total'
        FROM tabla
);

DROP temporary table IF EXISTS categoriaBR3;
CREATE TEMPORARY TABLE IF NOT EXISTS categoriaBR3 AS ( 
    SELECT 3 as id, ifnull(sum(case when categoriaBR = 'C' then 1 else 0 end),0) as 'Total'
        FROM tabla
);

#------------------------------------------------categoriasCA------------------------------------------------
    DROP temporary table IF EXISTS categoriaCA4;
CREATE TEMPORARY TABLE IF NOT EXISTS categoriaCA4 AS ( 
    SELECT 1 as id, ifnull(sum(case when categoriaCA = 'A' then 1 else 0 end),0) as 'Total'
        FROM tabla
);

DROP temporary table IF EXISTS categoriaCA5;
CREATE TEMPORARY TABLE IF NOT EXISTS categoriaCA5 AS ( 
    SELECT 2 as id, ifnull(sum(case when categoriaCA = 'B' then 1 else 0 end),0) as 'Total'
        FROM tabla
);

DROP temporary table IF EXISTS categoriaCA6;
CREATE TEMPORARY TABLE IF NOT EXISTS categoriaCA6 AS ( 
    SELECT 3 as id, ifnull(sum(case when categoriaCA = 'C' then 1 else 0 end),0) as 'Total'
        FROM tabla
);

#---------------------------------------------------categoriasMX--------------------------------------------------
DROP temporary table IF EXISTS categoriaMX7;
CREATE TEMPORARY TABLE IF NOT EXISTS categoriaMX7 AS ( 
    SELECT 1 as id, ifnull(sum(case when categoriaMX = 'A' then 1 else 0 end),0) as 'Total'
        FROM tabla
);

DROP temporary table IF EXISTS categoriaMX8;
CREATE TEMPORARY TABLE IF NOT EXISTS categoriaMX8 AS ( 
    SELECT 2 as id, ifnull(sum(case when categoriaMX = 'B' then 1 else 0 end),0) as 'Total'
        FROM tabla
);

DROP temporary table IF EXISTS categoriaMX9;
CREATE TEMPORARY TABLE IF NOT EXISTS categoriaMX9 AS ( 
    SELECT 3 as id, ifnull(sum(case when categoriaMX = 'C' then 1 else 0 end),0) as 'Total'
        FROM tabla
);
#------------------------------------UNION DE TODO---------------------------------------------------------------    
select 'A' as Categoria, categoriaBR1.Total as TotalBR, categoriaCA1.Total as TotalCA, categoriaMX1.Total as TotalMX from categoriaBR1
        INNER JOIN categoriaCA1 ON categoriaBR1.id = categoriaCA1.id
        INNER JOIN categoriaMX1 ON categoriaBR1.id = categoriaMX1.id
    union all
select 'B' as Categoria, categoriaBR2.Total as TotalBR, categoriaCA2.Total as TotalCA, categoriaMX2.Total as TotalMX from categoriaBR2
        INNER JOIN categoriaCA2 ON categoriaBR2.id = categoriaCA2.id
        INNER JOIN categoriaMX2 ON categoriaBR2.id = categoriaMX2.id
    union all
select 'C' as Categoria, categoriaBR3.Total as TotalBR, categoriaCA3.Total as TotalCA, categoriaMX3.Total as TotalMX from categoriaBR3
        INNER JOIN categoriaCA3 ON categoriaBR3.id = categoriaCA3.id
        INNER JOIN categoriaMX3 ON categoriaBR3.id = categoriaMX3.id

cabe mencionar que con la creación de las 9 tablas temporales obtengo el resultado que quiero mas la idea que tengo es llegar al mismo resultado sin tanta tabla temporal

3
  • @Flxtr Hice 9 tablas temporales sumando el total por categoría, les agregué un ID a las temporales, después les hice un inner join para obtener el totalBR, totalCA, totalMX por categoría y uni las categorías con union all pero siento que me la estoy complicando
    – El Cóndor
    el 21 feb. 2018 a las 4:20
  • Tienes razón quizás no lo agregue en un principio porque siento que estoy creando una tormenta en un vaso de agua con tanta tabla temporal pero ya hice la actualización y ya agregue lo que tengo, cabe mencionar que con lo que hice obtengo el resultado deseado mas me gustaría obtener el mismo resultado pero sin tanta tabla temporal
    – El Cóndor
    el 21 feb. 2018 a las 4:56
  • @ElCóndor Te deje un ejemplo para que lo puedas hacer más simple, eficiente y elegante. el 21 feb. 2018 a las 8:14

1 respuesta 1

3

Necesitas tratar los datos como si fuera una tabla de tipo pivote. Se hace de la siguiente manera:

SELECT
  category,
  COUNT(CASE WHEN country = 'BR' THEN 1 ELSE NULL END) AS 'BR',
  COUNT(CASE WHEN country = 'CA' THEN 1 ELSE NULL END) AS 'CA',
  COUNT(CASE WHEN country = 'MX' THEN 1 ELSE NULL END) AS 'MX'
FROM foo
GROUP BY category
ORDER BY category;

Te dejo el ejemplo funcionando aquí en sqlfiddle.

1
  • 1
    Eso es exactamente lo que necesitaba, como me lo imagine me la estaba complicando demasiado y de la forma en que tu lo haces es eficiente, simple y elegante como mencionas, muchas gracias!
    – El Cóndor
    el 21 feb. 2018 a las 13:17

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.