Provo a creare una tabella pivot che include solo stringhe.come sostituire i valori NULL nella tabella pivot?
Questa è una semplice versione del mio tavolo:
CREATE TABLE SecurityGroup (GroupName VARCHAR(20), SecLevel VARCHAR(20), Power VARCHAR(20))
INSERT INTO SecurityGroup
SELECT 'GroupA','Level1','read'
UNION
SELECT 'GroupA','Level2','write'
UNION
SELECT 'GroupA','Level3','read'
UNION
SELECT 'GroupA','Level4','read'
UNION
SELECT 'GroupA','Level4','write'
voglio usare la funzione PIVOT ottenere le seguenti Resultset
Expectation
GroupName Level1 Level2 Level3 Level4
GroupA read write read read
GroupA read write read write
Il problema che ho è che i valori per Level1 - Level3 esistono solo 1 volta, mentre Level4 ha 2 valori diversi. Così sto ottenendo sempre questo gruppo di risultati:
Realtà
GroupName Level1 Level2 Level3 Level4
GroupA read write read read
GroupA NULL NULL NULL write
sto usando questo codice
SELECT
[GroupName],
[Level1],
[Level2],
[Level3],
[Level4]
FROM
(SELECT
[GroupName],
[SecLevel],
[Power],
ROW_NUMBER() OVER(PARTITION BY [GroupName], [SecLevel] ORDER BY [Power]) AS rn
FROM [SecurityGroup]) AS SourceTable
PIVOT
(MAX([Power])
FOR [SecLevel]
IN ([Level1], [Level2], [Level3], [Level4])
) AS PivotTable
Delle idee come risolvere questo problema? Non riesco ad aggiungere altri valori per Level1 - Level3 nella tabella di origine.
Ho già provato a utilizzare RANK() invece di ROW_NUMBER() ma non ha funzionato.
Grazie per il vostro aiuto.
Un dolore da scrivere, ma la mia idea è quella di utilizzare una tabella CTE o temporanea in cui si aggiungono valori per Level1 - Level3, quindi selezionare dal CTE anziché dalla tabella. La tabella attuale non deve essere cambiata. Dovrebbe esserci qualcosa di più elegante, ma non mi viene in mente. –
guardando il risultato in ingresso impostato, il tuo PIVOT sta restituendo il risultato corretto! in pratica hai due gruppi diversi sebbene entrambi siano chiamati GroupA. uno ha un valore per tutti e 4 i livelli e uno ha solo per il livello 4. –
btw, perché stai generando un RowNumber e non lo utilizzi da nessuna parte? –