SELECT count avec Group by et select dernière valeur not null
Bonjour,
J'ai un petit problème avec ma requête soit elle est pas assez performante soit j'ai une petite erreur mais je suis pas sûr que cette requête est correcte.
J'ai 3 tables que voici :
Citation:
1) Documents
DocRef CustRef
Doc1 Cust1
Doc2 Cust2
Doc3 Cust1
2) LinkInter
DocRef InterRef
Doc1 Inter1
Doc2 Inter2
Doc3 Inter3
3) Inter
id InterRef deliverychannel email mobilenb date status
1 Inter1 Email
email1@email.be 2013-01-14T00:00:00Z ok
2 Inter1 SMS 0444111111 2013-01-12T00:00:00Z ko
3 Inter1 Other
email5@email.be 2013-02-21T00:00:00Z ko
4 Inter2 Email
email2@email.be 044456465465 2013-01-21T00:00:00Z ko
5 Inter3 Email 2013-01-21T00:00:00Z ko
6 Inter3 SMS 2013-01-22T00:00:00Z ko
7 Inter3 Other
email3@mail.be 2013-01-22T00:00:00Z ko
pour une vue meilleure voici structure de la table et données : http://sqlfiddle.com/#!9/16649f/15
voici le résultat que je voudrai avoir:
Citation:
CustRef | number of InterRef SMS KO| Last email known| Last mobilenb known
Cust1 | 2 |
email5@email.be | 0444111111
j'avais tenté avec 2 fonctions qui allait rechercher le dernier email connu (différent de null ou vide) ainsi que le numéro de mobile mais c'était hyper lent étant donné que mes tables ont plus de 10 millions de records
ensuite j'ai tenté ceci :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| SELECT d.CustRef, count(DISTINCT i.InterRef) as 'NbTotalKOByCustomer', t2.lastEmailKnown, t3.lastmobileNumberKnown
FROM Documents d
INNER join LinkInter link on link.DocRef = d.DocRef
INNER join Inter i on i.InterRef = link.InterRef and i.DeliveryChannel = 'SMS' and i.status = 'ko'
LEFT JOIN (SELECT distinct i2.email as lastEmailKnown, d2.CustRef
FROM Inter i2
INNER join LinkInter link2 on link2.InterRef = i2.InterRef
INNER join Documents d2 on d2.DocRef = link2.DocRef
where i2.email is not NULL and i2.email <> '' group by d2.CustRef ORDER by i2.date DESC
) t2 on t2.CustRef = d.CustRef
LEFT JOIN (SELECT distinct i3.mobilenb as lastmobileNumberKnown, d3.CustRef
FROM Inter i3
INNER join LinkInter link3 on link3.InterRef = i3.InterRef
INNER join Documents d3 on d3.DocRef = link3.DocRef
where i3.mobilenb is not NULL and i3.mobilenb <> '' group by d3.CustRef ORDER by i3.date DESC
) t3 on t3.CustRef = d.CustRef
-- WHERE d.CustRef = 'Cust1'
Group by d.CustRef HAVING count(DISTINCT i.InterRef) > 1
Order by d.CustRef DESC; |
mais j'ai une erreur il me sort email1@email.be et non email5@email.be
J'allias oublié de traduire ce que je veux faire :)
Je veux récupérer tous les clients où le deliverychannel = SMS et le status = ko, le nombre d'inter (interactions) avec le status ko, le dernier mail connu et dernier numéro de mobile connu (qui ne soit pas null ou vide)
Est-ce que vous pourriez m'aider à résoudre mon problème ?
Y a t'il un autre moyen de faire plus performant?
Déjà un grand merci d'avance pour votre aide !