PIVOT / UNPIVOT in SQL Server 2008

后端 未结 2 1670
有刺的猬
有刺的猬 2021-01-17 05:43

I got child / parent tables as below.

MasterTable:

MasterID, Description

ChildTable

ChildID, MasterID, Description.         


        
2条回答
  •  难免孤独
    2021-01-17 05:59

    It greatly depends on whether the number of crosstabbed columns is fixed. If they are, then you can simply do something like:

    Select ParentDesc
        , [1] As ChildId1
        , [Description1] As ChildDescription1
        , [2] As ChildId2
        , [Description2] As ChildDescription2
        , [3] As ChildId3
        , [Description3] As ChildDescription3
    From    (
            Select C.Id As ChildId, C.Description As ChildDesc, P.Description As ParentDesc
            From ChildItems As C
                Join ParentItems As P
                    On P.Id = C.ParentId
            ) As C
    Pivot   (
            Count(ChildId)
            For ChildId In([1],[2],[3])
            ) As PVT0
    Pivot   (
            Count(ChildDesc)
            For ChildDesc In([Descripion1],[Descripion2],[Descripion3])
            ) As PVT1
    

    There is also a way of achieving similar results use CASE functions.

    However, if what you want is to have the number of crosstab columns determined at runtime, then the only means to do that inside of SQL Server is to use some fugly dynamic SQL. This is outside the realm of SQL Server's primary purpose which is to serve up data (as opposed to information). If you want a dynamic crosstab, I would recommend not doing it in SQL Server but instead use a reporting tool or build your result set in a middle-tier component.

提交回复
热议问题