Come trovare il conto di transazioni di tipo 1 e di tipo 2 per ogni cliente in mysql

StackOverflow https://stackoverflow.com/questions/1465160

  •  13-09-2019
  •  | 
  •  

Domanda

Ho una tabella cliente:

id   name
1    customer1
2    customer2
3    customer3

e una tabella di transazione:

id   customer   amount   type
1    1          10       type1
2    1          15       type1
3    1          15       type2
4    2          60       type2
5    3          23       type1

Quello che voglio la mia domanda a tornare è la seguente tabella

name        type1    type2
customer1   2        1
customer2   0        1
customer3   1        0

Il che dimostra che Customer1 ha fatto due operazioni di tipo 1 e 1 delle transazioni di tipo 2 e così via.

C'è una domanda che posso usare per ottenere questo risultato o devo usare codice procedurale.

È stato utile?

Soluzione

Si potrebbe provare

select c.id as customer_id
   , c.name as customer_name
   , sum(case when t.`type` = 'type1' then 1 else 0 end) as count_of_type1
   , sum(case when t.`type` = 'type2' then 1 else 0 end) as count_of_type2
from customer c
   left join `transaction` t
   on c.id = t.customer
group by c.id, c.name

Questa query ha bisogno di iterare solo una volta nel corso del join.

Altri suggerimenti

dirk mi ha battuto ad esso;)

Simile ma lavorerà in MySQL 4.1 anche.

Select c.name,
sum(if(type == 1,1,0)) as `type_1_total`,
sum(if(type == 2,1,0)) as `type_2_total`,
from 
customer c
join transaction t on (c.id = t.customer)
;
SELECT  name, 
        (
        SELECT  COUNT(*)
        FROM    transaction t
        WHERE   t.customer = c.id
                AND t.type = 'type1'
        ) AS type1,
        (
        SELECT  COUNT(*)
        FROM    transaction t
        WHERE   t.customer = c.id
                AND t.type = 'type2'
        ) AS type2
FROM    customer c

Per applicare condizioni WHERE a queste colonne utilizzare questo:

SELECT  name
FROM    (
        SELECT  name, 
                (
                SELECT  COUNT(*)
                FROM    transaction t
                WHERE   t.customer = c.id
                        AND t.type = 'type1'
                ) AS type1,
                (
                SELECT  COUNT(*)
                FROM    transaction t
                WHERE   t.customer = c.id
                        AND t.type = 'type2'
                ) AS type2
        FROM    customer c
        ) q
WHERE   type1 > 3
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top