Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Problem beim Zählen der Elementhäufigkeit in T-SQL

Wenn Sie SQL Server 2005+ verwenden

With 
    WinnerCounts As
    (
        Select #Numbers.Number, Count(Results.Winner) As Results
        FROM #Numbers
            JOIN Results 
                On #Numbers.Number = Results.Winner 
    )
    , SecondCounts As
    (
        Select #Numbers.Number, Count(Results.Second) As Results
        FROM #Numbers
            JOIN Results 
                On #Numbers.Number = Results.Second
    )
    , ThirdCounts As
    (
        Select #Numbers.Number, Count(Results.Third) As Results
        FROM #Numbers
            JOIN Results 
                On #Numbers.Number = Results.Third
    )
Select Numbers.Number, Coalesce(WinnerCounts.Results,0) As Winner, Coalesce(SecondCounts.Result,0) As Second, Coalesce(ThirdCounts.Result,0) As Third
From #Numbers
    Left Join WinnerCounts
        On WinnerCounts.Results = #Numbers.Number
    Left Join SecondCounts
        On SecondCounts.Results = #Numbers.Number
    Left Join ThirdCounts
        On ThirdCounts.Results = #Numbers.Number

Eine weitere mögliche Lösung, die in älteren Versionen von SQL Server funktioniert:

Select #Numbers.Number
    , SUM( Case When Winners.Winner Is Not Null Then 1 Else 0 End ) As WinnerCount
    , SUM( Case When Seconds.Second Is Not Null Then 1 Else 0 End ) As SecondCount
    , SUM( Case When Thirds.Third Is Not Null Then 1 Else 0 End ) As ThirdCount
From #Numbers
    Left Join Results As Winners
        On Winners.Winner = #Numbers.Number
    Left Join Results As Seconds
        On Seconds.Second = #Numbers.Number
    Left Join Results As Thirds
        On Thirds.Third = #Numbers.Number
Group By #Numbers.Number