how to convert row to column in SQL

前端 未结 3 1524
北荒
北荒 2021-01-23 20:05

Can somebody help me with this SQL Query.

In the following table, RESPONSES counts how many times SEGMENT has responded on CHECKED date.

CREATE TABLE #         


        
3条回答
  •  礼貌的吻别
    2021-01-23 20:24

    Select Checked
        , Sum( Case When Segment = 'A' Then 1 Else 0 End ) As A
        , Sum( Case When Segment = 'B' Then 1 Else 0 End ) As B
        , Sum( Case When Segment = 'C' Then 1 Else 0 End ) As C
    From #Test
    Group By Checked
    

    This type of query is often called a crosstab query. The above solution assumes you want to statically declare which columns you want to see. If you want to dynamically determine the columns, then what you seek is a dynamic crosstab and it cannot be done natively in the SQL language. The SQL language was not designed for dynamic column generation. The solution is to build the query in your middle-tier.

提交回复
热议问题