Domanda
Ho il seguente set di risultati:
Tipo | metodo | Importo
Type1 Contanti
Type1 Controllare Importo
Tipo2 Contanti
Tipo2 Controllare Importo
Type3 Contanti
Type3 Controllare Importo
E voglio farlo sembrare come questo:
Tipo | Cash | Controllare
Type1 Importo Importo
Tipo2 Importo
Type3 Importo
Come posso raggiungere questo obiettivo in T-SQL (2005 sintassi ok)? Ho bisogno di ruotare per tipo (1, 2, 3 ...)
Soluzione
Ecco un tentativo di PIVOT:
select *
from YourTable
PIVOT (sum(amount) FOR Method in (Cash,Check)) as Y
Dato che si tratta di solo due colonne, potrebbe provare con un join:
select
type
, cash = a.amount
, check = b.amount
from yourtable a
full join yourtable b on a.type = b.type
where a.method = 'cash' or b.method = 'Check'
Altri suggerimenti
O meglio ancora:
select
Type
, Cash = sum(case when Method = 'Cash' then Amount end)
, Check = sum(case when Method = 'Check' then Amount end)
from yourtable
group by
Type
Aggiungi un ELSE 0 alle dichiarazioni CASE se del caso.
Questa forma è più flessibile del operatore PIVOT e non necessita di unione completa. aggregazione solo dritto.