透视方法的帮助

时间:2019-07-08 13:59:50

标签: sql-server

Help在数据透视方法中,我不想继续写所有ID,有没有一种方法可以像这样做到而又不写所有ID

我不知道

ObjectName
ObjectValue

我希望看到没有(SELECT 'Montant' AS IdClient, * FROM ( SELECT MontantTransaction,IdClient FROM Transactions ) AS TableSource PIVOT ( Sum(MontantTransaction) FOR IdClient IN( [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24]) ) AS TableDePivot;

1 个答案:

答案 0 :(得分:0)

尝试一下-

样品温度表和数据

Create Table #Transactions 
(

    IdClient varchar(3),
    MontantTransaction decimal(10,2)
)

insert into #Transactions values (1, 1000.00)
insert into #Transactions values (1, 200.00)
insert into #Transactions values (2, 800.00)
insert into #Transactions values (2, 700.00)
insert into #Transactions values (3, 1100.00)
insert into #Transactions values (4, 1400.00)

查询

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.IdClient) 
            FROM #Transactions c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ''Montant'' AS IdClient, ' + @cols + ' from 
            (
                select 
                    MontantTransaction
                    , IdClient
                from #Transactions
           ) x
            pivot 
            (
                 Sum(MontantTransaction)
                for IdClient in (' + @cols + ')
            ) p '


execute(@query)

drop table #Transactions