sql >> データベース >  >> RDS >> Sqlserver

T-SQLでアイテムの頻度をカウントする際の問題

    SQLServer2005以降を使用している場合

    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
    

    古いバージョンのSQLServerで機能する別の可能な解決策:

    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
    


    1. 別のアプリケーションからのMySQL挿入を監視する

    2. 大きなテーブルから親ごとに最新の子を取得します-クエリが遅すぎます

    3. 整数以外の整数の入力構文が無効ですか?

    4. MySQLまたはMariaDBデータベースをSQLインジェクションから保護する方法:パート2