2016-06-01 20 views
-1

Ich habe die folgende Tabellegibt es die erste Not Null Wert mit einer Gruppe

Source Table

Es folgt das Ergebnis, das ich

Result Set

Erklärung

zu erreichen versuche, Ich möchte die Daten nach Standort gruppieren und die Faust bekommen Nicht Nullwert, der in der Spalte verfügbar ist. Zum Beispiel für locationcd 1300 die Spalte A den Wert John, Spalte B den Wert John, Spalte C haben den Wert Taylor und Spalte D haben haben den Wert Brian haben.

Meine Lösung

Ich habe etwas, das nicht das richtige Ergebnis garantiert. Hier ist meine Abfrage

select locationCd, 
min([$1-$500]), 
min([$501-$2500]) as '$501-$2500', 
Min([$2501-$5000]) as '$2501-$5000', 
min([$$5000 and above]) as '$$5000 and above' 
from #tab 
group by LocationCd 

Bitte helfen.

+0

geben Sie bitte gültige Daten es wird Ihnen helfen, bessere Antwort zu bekommen – mohan111

+0

Zuerst? Jetzt kommt ein Kampf mit Fragen wie welche Spalte die Reihenfolge bestimmt. Aus Ihren Daten kann einfach gefiltert werden mit allen Spalten 'not null' –

+0

Das Ergebnis stimmt nicht mit den Geschäftsregeln überein? –

Antwort

0

Unten Abfrage wird das gewünschte Ergebnis geben: -

select ROW_NUMBER() OVER (partition by locationCd order by locationCd) RID,locationCd,A,B,C,D into #t1 from table_name 

select locationcd,min(A) A, 
(select B from #t1 b where b.locationcd=a.locationcd AND b.RID=3) B, 
(select C from #t1 c where c.locationcd=a.locationcd AND c.RID=2) C, 
(select D from #t1 d where d.locationcd=a.locationcd AND d.RID=1) D 
from #t1 a 
group by locationcd 

drop table #t1 

Ausgang: -

locationcd A  B  C  D 
200  David David Detlef Brian 
201  David David Detlef Brian 
400  Walter Brad Detlef Brian 
1200  David David Detlef Brian 
1300  John John Taylor Brian 
1400  Walter Brad Detlef Brian 

table_name Ersetzen durch erforderliche Tabelle

0
Select LocationId, MAX(Ty1.A) A 
From #tabl T01 
Outer Apply (Select Top 1 A From #tabl T1 Where T1.LocationId=T01.LocationId And T1.A Is Not Null) Ty1 
Group By LocationId 

hilft Ihnen das ???

0
;with cte as 
(select distinct locid from @t) 
select cte.locid, 
    (select top 1 cola from @t t where t.locid = cte.locid AND t.cola is not null) cola , 
     (select top 1 colb from @t t where t.locid = cte.locid AND t.colb is not null) colb, 
     (select top 1 colc from @t t where t.locid = cte.locid AND t.colc is not null) colc, 
     (select top 1 cold from @t t where t.locid = cte.locid AND t.cold is not null) cold 
from cte 
0

Versuchen Sie es ,. Hoffe, das hilft Ihnen, ...

select LocationCD,min(A),min(B),min(C),min(D) 
from #tab 
group by LocationCD 
Verwandte Themen