2016-06-28 7 views
-1

Ich habe die Ausgabe einer Abfrage wie folgtSQL Server: Gruppenzeilen mit demselben Wert und einer anderen Zeile

Acct#  OwnerType TotalBal Type1Bal Type2Bal Type3Bal 
    -------------------------------------------------------------- 
    1234  Type1  0   1000   0   
    1234  Type2  0    0  1000 
    1234  Type3  0    0   0  1000 
    123456 Type1  0   2000   0   0 
    123456 Type2  0    0  2000   0 
    123456 Type3  0    0   0  2000 

Diese die durch eine Abfrage erzeugt Abtastdaten ist. Für jede Kontonummer benötige ich eine Kopfzeile (etwa so), Zeile mit Gesamtsaldo mit dem eigentlich nur einen der drei Salden. Kann mir jemand die richtige Richtung vorschlagen oder zeigen?

Acct#  OwnerType TotalBal Type1Bal Type2Bal Type3Bal 
    ------------------------------------------------------------------- 
    1234  TotalAmt 1000   0   0  0 
    1234  Type1  0  1000   0  0 
    1234  Type2  0   0   1000  0 
    1234  Type3  0   0   0 1000 
    123456 TotalAmt 2000   0   0  0 
    123456 Type1  0  2000   0  0 
    123456 Type2  0   0   2000  0 
    123456 Type3  0   0   0 2000 

Antwort

0
Declare @Table table (Acct int,OwnerType varchar(25),TotalBal int,Type1Bal int,Type2Bal int,Type3Bal int) 
Insert into @Table values 
(1234  ,'Type1',  0,   1000,   0 ,  null), 
(1234  ,'Type2',  0 ,   0 ,  1000,  null), 
(1234  ,'Type3',  0 ,   0 ,   0 ,  1000), 
(123456 ,'Type1',  0 ,   2000 ,  0 ,  0), 
(123456 ,'Type2',  0 ,   0 ,  2000 ,  0), 
(123456 ,'Type3',  0 ,   0 ,   0 ,  2000) 


Select Acct,OwnerType='TotalAmt',TotalBal=max(Type1Bal),Type1Bal=0,Type2Bal=0,Type3Bal=0 From @Table Group By Acct 
Union All 
Select Acct,OwnerType,TotalBal=0,Type1Bal=isnull(Type1Bal,0),isnull(Type2Bal,0),IsNull(Type3Bal,0) from @Table 
Order By Acct,OwnerType 

Returns

Acct OwnerType TotalBal Type1Bal Type2Bal Type3Bal 
1234 TotalAmt 1000  0   0   0 
1234 Type1  0   1000  0   0 
1234 Type2  0   0   1000  0 
1234 Type3  0   0   0   1000 
123456 TotalAmt 2000  0   0   0 
123456 Type1  0   2000  0   0 
123456 Type2  0   0   2000  0 
123456 Type3  0   0   0   2000 
Verwandte Themen