sql >> Base de Datos >  >> RDS >> Sqlserver

Problema al contar la frecuencia de elementos en T-SQL

Si está utilizando SQL Server 2005+

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

Otra posible solución que funcionará en versiones anteriores de SQL Server:

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