-1

Help In the pivot method , i dont want to keep writing all the Id is there a way to Like Do it without writing all the id

I dont know how

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;

i expect to see this code without the ( [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13]....

John Cappelletti
  • 79,615
  • 7
  • 44
  • 66

1 Answers1

0

Try this -

Sample Temp Table & Data

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)

Query

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
Mukesh Arora
  • 1,763
  • 2
  • 8
  • 19
  • can u please explain for me what does SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(NomClient) FROM Client FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') – Younes Harir Jul 08 '19 at 15:00
  • This will return [1],[2],[3],[4] based on sample table data and which will be used to generate a dynamic pivot table. you can print @cols to see the result. – Mukesh Arora Jul 09 '19 at 04:07