2017-09-12 3 views
1
Consolidation

I ont une table semblable à ceci:lignes en colonnes

Match | Quarter | Profit 
-------+---------+-------- 
    1 | First | 10.00 
    1 | Second | 14.00 
    2 | First | 22.00 
    1 | Last | 11.00 
    2 | Second | 18.00 
    2 | Third | 16.00 
    2 | Last | 10.00 

Je veux y parvenir:

Match | First Profit | Second Profit | Third Profit | Last Profit 
-------+--------------+---------------+--------------+--------------- 
    1 | 10.00  | 14.00   |0.00   |11.00 
    2 | 22.00  | 18.00   |16.00   |10.00 

En mots simples consolider les lignes en un seul. Important que si aucune valeur n'est trouvée pour un trimestre, le résultat est enregistré comme 0.00;

Vous ne savez pas comment cela peut être réalisé avec une fonction CROSSTAB? J'ai lu autour de moi et j'ai eu du mal à trouver une bonne réponse ou une bonne solution.

Merci d'avance pour toute aide.

Répondre

0

Cela devrait faire:

SELECT Match 
    , sum(case when Quarter = 'First' then Profit else 0.00 end) as first_profit 
    , sum(case when Quarter = 'Second' then Profit else 0.00 end) as second_profit 
    , sum(case when Quarter = 'Third' then Profit else 0.00 end) as third_profit 
    , sum(case when Quarter = 'Last' then Profit else 0.00 end) as last_profit 
FROM data 
GROUP BY match 
ORDER BY Match 

Voici un exemple avec vos données d'échantillon:

with data as (
select 
1 as match, 'First' as Quarter, 10.00 as Profit 
union 
select 
1 as match, 'Second' as Quarter, 14.00 as Profit 
union 
select 
2 as match, 'First' as Quarter, 22.00 as Profit 
union 
select 
1 as match, 'Last' as Quarter, 11.00 as Profit 
union 
select 
2 as match, 'Second' as Quarter, 18.00 as Profit 
union 
select 
2 as match, 'Third' as Quarter, 16.00 as Profit 
union 
select 
2 as match, 'Last' as Quarter, 10.00 as Profit 
) 
SELECT Match 
    , sum(case when Quarter = 'First' then Profit else 0.00 end) as first_profit 
    , sum(case when Quarter = 'Second' then Profit else 0.00 end) as second_profit 
    , sum(case when Quarter = 'Third' then Profit else 0.00 end) as third_profit 
    , sum(case when Quarter = 'Last' then Profit else 0.00 end) as last_profit 
FROM data 
GROUP BY match 
ORDER BY Match 
+0

solution brillante, merci beaucoup! – Harry