Wie Anzahl der Transaktion von Typ1 und Typ2 für jeden Kunden in mysql finden
-
13-09-2019 - |
Frage
Ich habe einen Kunden Tabelle:
id name
1 customer1
2 customer2
3 customer3
und eine Transaktionstabelle:
id customer amount type
1 1 10 type1
2 1 15 type1
3 1 15 type2
4 2 60 type2
5 3 23 type1
Was ich will, meine Frage ist die folgende Tabelle zurück
name type1 type2
customer1 2 1
customer2 0 1
customer3 1 0
Welche zeigt, dass customer1 zwei Transaktionen von Typ1 und 1 Transaktion von Typ2 gemacht hat und so weiter.
Gibt es eine Abfrage, die ich verwenden kann, um dieses Ergebnis zu erhalten, oder muss ich prozeduralen Code verwenden.
Lösung
Sie könnten versuchen,
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
Diese Abfrage nur einmal zu durchlaufen muss über die Verbindung.
Andere Tipps
dirk schlug mich zu ihm;)
Ähnlich, aber wird in MySQL 4.1 arbeiten.
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
Um WHERE
Bedingungen gelten für diese Spalten verwenden diese:
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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow