1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| ------------------------------------------------------------------------DEBUT------------------------------------------------------------------------
WITH scoring as (
SELECT
code_produit as produit,
code_ville as ville,
code_activite as activite,
raisonsociale as client,
montant_ht,
annee_emission_facture
FROM facturation f
, rang AS (
SELECT client,
SUM(montant_ht) AS montant_ht,
RANK() OVER (ORDER BY SUM(montant_ht) DESC) as rank2
FROM scoring
GROUP BY client
)
, rang1 AS (
SELECT r.client,
S1.produit,
SUM(s1.montant_ht) as montant_ht,
rank2
FROM scoring s1
INNER JOIN rang r on r.client = s1.client
GROUP BY r.client,
S1.produit,
r.rank2
)
, selection AS (
SELECT client,
montant_ht,
produit,
rank2
FROM rang1
WHERE rank2 <=5
)
------------------------------------------------------------------------FIN ------------------------------------------------------------------------
SELECT * FROM (
---PAR PRODUIT
SELECT client,
produit,
SUM(montant_ht) as montant_ht,
rank2
FROM selection
GROUP BY client,produit,rank2
UNION
---TOTAL PAR CLIENT
SELECT client,
'Y_Total' as produit,
SUM(montant_ht) as montant_ht,
rank2
FROM selection
GROUP by client,rank2
UNION
---Client total : par produit
SELECT 'Z_Total' as client,
produit,
SUM(montant_ht) as montant_ht,
0 as rank2
FROM selection
GROUP by produit
UNION
---Client total : tous produits
SELECT 'Z_Total' as client,
'Y_Total' as produit,
SUM(montant_ht) AS montant_ht,
0 as rank2
FROM selection
UNION
--- % par client
SELECT A.client as client,
'Z_% / total'::varchar(255) as produit,
A.montant_ht / ( SELECT SUM(montant_ht) AS montant_ht FROM selection) as montant_ht,
A.rank2
FROM (
SELECT
client,
'Z_% / total' as produit,
SUM(montant_ht) as montant_ht,
rank2
FROM selection
GROUP by client,rank2
)A
UNION
--- % Total
SELECT
'Z_Total' as client,
'Z_% / total' as produit,
1 as montant_ht,
0 as rank2
FROM selection
)globale |
Partager