I have a request which returns something like this:
--------------------------
Tool | Week | Value
--------------------------
Test | 20 | 3
Sense | 20 | 2
Test | 19 | 2
And I want my input to look like this:
-------------------------
Tool | W20 | W19
-------------------------
Test | 3 | 2
Sense | 2 | null
Basically, for every week I need to have a new column. The number of week and of tools is dynamic.
I have tried many things but nothing worked. Anybody have a solution ?
Try this
CREATE table #tst (
Tool varchar(50), [Week] int, Value int
)
insert #tst
values
('Test', 20, 3),
('Sense', 20,2),
('Test', 19, 2)
Here is the Dynamic Query:
DECLARE #col nvarchar(max), #query NVARCHAR(MAX)
SELECT #col = STUFF((SELECT DISTINCT ',' + QUOTENAME('W' + CAST([Week] as VARCHAR))
from #tst
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query = '
SELECT *
FROM (
SELECT Tool,
Value,
''W'' + CAST([Week] as VARCHAR) AS WeekNo
FROM #tst
) t
PIVOT
(
MAX(t.Value)
FOR WeekNo IN (' + #col + ')
) pv
ORDER by Tool'
EXEC (#query)
Result
Tool W20 W19
=================
Sense 2 NULL
Test 3 2
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
( Tool varchar(5), Week int, Value int)
;
INSERT INTO #temp
( Tool , Week , Value )
VALUES
('Test', 20, 3),
('Sense', 20, 2),
('Test', 19, 2)
;
DECLARE #statement NVARCHAR(max)
,#columns NVARCHAR(max),
#col NVARCHAR(max)
SELECT #columns = ISNULL(#columns + ', ', '') + N'[' +'w'+ tbl.[Week] + ']'
FROM (
SELECT DISTINCT CAST([Week] AS VARCHAR)[Week]
FROM #temp
) AS tbl
SELECT #statement = 'SELECT *
FROM
(
SELECT
Tool , ''w''+ CAST(Week AS VARCHAR) week , Value
FROM
#Temp
) src
PIVOT(MAX(Value)for Week in (' + #columns + ')) as pvt
'
EXEC sp_executesql #statement = #statement
This is how I would do it ... If I understood your question correctly
if object_id('tempdb..#InputTool') is not null drop table #InputTool
create table #InputTool (Tool nvarchar(10), [20] int, [19] int)
insert into #InputTool (Tool, [20], [19])
values
('Test', 3, 2),
('Sense', 2, null)
declare #cols nvarchar(max)
select #cols = STUFF((SELECT ',' + QUOTENAME(name)
from tempdb.sys.columns
where object_id = object_id('tempdb..#InputTool')
and Column_id > 1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
declare #sqlquery nvarchar(max) =
'select Tool, Weeks, Value from (
select * from #InputTool
) as it
UNPIVOT
(
Value FOR Weeks IN (' + #cols + ')
) AS Weeks
order by Weeks desc'
execute (#sqlquery);
Give it a shot and let me know if it worked
Related
My quest might be answered in somewhere here but I couldn't find. So, sorry if I asked in vain.
I have a Table that's populate automatically with precisely date/time in SQL Server and looks like this:
Cod_Analise| Dat_analise | Nom_usuario| Resultado
-----------+-----------------+------------+-----------
1 | 02/20/2019 14:30| John | 4.5
2 | 02/20/2019 14:31| Carl | 60
3 | 02/21/2019 17:25| Carl | 17
2 | 02/19/2019 06:00| Marcus | 58
1 | 02/20/2019 15:40| Jorge | 5.2
2 | 02/21/2019 22:00| John | 58
and I need something like this:
Dat_Analise | 1 | 2 | 3 | Nom_usuario
------------+---+---+---+------------
02/19/2019 | 0 |58 | 0 | Marcus
02/20/2019 |4.9|60 | 0 | (First or Last one)
I need to do a pivot table based in this table where the Columns are Dat_Analise(date), Nom_operador(who did) and "Cod_Analise"(what did). And the rows are "Resultados"(results).
My problem is, i need to group by time period taking avg results for dynamic number of Cod_analises. But I even did the pivot with dynamic columns but I cannot fit the Group By part inside the pivot table.
I try to use a model that i found here and my procedure is like this:
SELECT
A.[RESULTADO],
A.[DAT_ANALISE],
A.[NOM_USUARIO],
B.[NOM_ANALISE]
into #temporaria
FROM
[BSDB_Processo].[dbo].[RESULTADOS_ANALISES] A,
[BSDB_Processo].[dbo].[ANALISES] B
WHERE
A.COD_PROCESSO = #PROCESSO
AND
A.COD_ANALISE = B.COD_ANALISE
AND
NUM_LOTE =#LOTE
Then:
declare #columnsSrc nvarchar(max) = N''
,#columnsDst nvarchar(max) = N''
,#sql nvarchar(max)
,#KeyColumns nvarchar(max) = N'DAT_ANALISE'
,#compatibility int = (
select top 1 compatibility_level from sys.databases
where name = db_name()
order by Name
);
declare #GroupBy nvarchar(max) =
--case when #compatibility <= 90
-- then case when len(#KeyColumns)=0 then '' else 'group by ' + #KeyColumns +
-- ' with rollup' end
-- else case when len(#KeyColumns)=0 then '' else 'group by rollup ('
-- + #KeyColumns + ')' end
-- end
case when len(#KeyColumns)=0 then '' else 'group by ' + #KeyColumns end;
select
#columnsSrc += nchar(10) + N',' + quotename([NOM_ANALISE])
,#columnsDst += nchar(10) + N',sum(isnull(' + quotename([NOM_ANALISE]) + N',0)) as '
+ quotename([NOM_ANALISE])
from (
select [NOM_ANALISE]
from #temporaria
group by [NOM_ANALISE]
) as x
order by x.[NOM_ANALISE]
And:
set #sql = N'
select ' +
case when len(#KeyColumns)=0 then '' else #KeyColumns + ',' end +
STUFF(#columnsDst, 1, 2, '') + '
INTO ##tabelaAnalises
from (
select' + nchar(10) +
case when len(#KeyColumns)=0 then '' else #KeyColumns + ',' end +
' [NOM_ANALISE],[RESULTADO]
from #temporaria
) as j
pivot (
sum([RESULTADO]) for [NOM_ANALISE] in ('
+ stuff(replace(#columnsSrc, ',p.[', ',['), 2, 1, '')
+ ')
) as p' + nchar(10) +
#GroupBy +
';'
>;
--print #sql;
exec sp_executesql #sql;
select * from ##tabelaAnalises
commit
End
Hope you can help me guys and ,again, sorry if i did something wrong with this post. First time using this
Try to see the below query. Please, see UPDATE section of a pivot with column Nom_usuario.
Sample data:
IF OBJECT_ID('tempdb..#SomeTable') IS NOT NULL DROP TABLE #SomeTable
GO
CREATE TABLE #SomeTable
(
Cod_Analise int,
Dat_analise datetime,
Nom_usuario varchar(50),
Resultado numeric(18,1)
)
INSERT INTO #SomeTable
(
Cod_Analise,
Dat_analise,
Nom_usuario,
Resultado
)
VALUES
( 2, '20190219 06:00', 'Marcus', 58)
, ( 1, '20190220 14:30', 'John', 4.5)
, ( 2, '20190220 14:31', 'Carl', 60)
, ( 1, '20190220 15:40', 'Jorge', 5.2)
, ( 3, '20190221 17:25', 'Carl', 17)
, ( 2, '20190221 22:00', 'John', 58)
A query:
SELECT
pvt.Dat_analise
, pvt.[1]
, pvt.[2]
, pvt.[3]
FROM
(SELECT
CONVERT(date, (t.Dat_analise)) Dat_analise
, t.Cod_Analise
, t.Resultado
FROM #SomeTable t) AS t
PIVOT
(
AVG(T.Resultado)
FOR t.Cod_Analise IN ([1], [2], [3])
) pvt
And dynamic version:
declare #cols nvarchar(max);
declare #sql nvarchar(max);
select #cols = stuff((
select distinct
' , ' + CONCAT('[', CONVERT(varchar(10), t.Cod_Analise), ']')
from #SomeTable t
order by 1
for xml path (''), type).value('.','nvarchar(max)')
,1,2,'')
select #sql = '
select p.Dat_Analise,' + #cols + '
from (
SELECT
CONVERT(date, (t.Dat_analise)) Dat_analise
, t.Cod_Analise
, t.Resultado
FROM #SomeTable t
) as t
pivot (AVG(T.Resultado)
FOR t.Cod_Analise in (' + #cols + ') ) p'
exec(#sql);
OUTPUT:
Dat_analise 1 2 3
2019-02-19 NULL 58.000000 NULL
2019-02-20 4.850000 60.000000 NULL
2019-02-21 NULL 58.000000 17.000000
UPDATE:
Use the following code snippet to show a Nom_usuario:
declare #cols nvarchar(max);
declare #sql nvarchar(max);
select #cols = stuff((
select distinct
' , ' + CONCAT('[', CONVERT(varchar(10), t.Cod_Analise), ']')
from SomeTable t
order by 1
for xml path (''), type).value('.','nvarchar(max)')
,1,2,'')
select #sql = '
select *
from
(
SELECT
CONVERT(date, (t.Dat_analise)) Dat_analise
, t.Cod_Analise
, t.Resultado
, MAX(t.Nom_usuario) OVER (PARTITION BY CONVERT(DATE, (t.Dat_analise))) Nom_usuario
FROM SomeTable t
) as t
pivot (AVG(T.Resultado)
FOR t.Cod_Analise in (' + #cols + ') ) p'
exec(#sql);
OUTPUT:
Dat_analise Nom_usuario 1 2 3
2019-02-21 John NULL 58.000000 17.000000
2019-02-20 Jorge 4.850000 60.000000 NULL
2019-02-19 Marcus NULL 58.000000 NULL
I want to create sql query result. I want to dynamically create because of inventory locations are one or more. (Example.. CTE)
Item_id Location Qty
--------------------------
1 a 1
2 b 2
3 c 3
3 a 1
2 c 2
1 b 3
Result is....
Item_id a_Location_Qty b_Location_Qty c_Location_Qty
-------------------------------------------------------
1 1 3 0
2 0 2 2
3 1 0 3
Please try below code
Create Table #Stack10072017040904(Item_id varchar(100),Location varchar(100),Qty int)
insert into #Stack10072017040904 select '1','a','1'
insert into #Stack10072017040904 select '2','b','2'
insert into #Stack10072017040904 select '3','c','3'
insert into #Stack10072017040904 select '3','a','1'
insert into #Stack10072017040904 select '2','c','2'
insert into #Stack10072017040904 select '1','b','3'
select Item_id,Isnull(a,0) a_Location_Qty
,isnull(b,0)b_Location_Qty
,isnull(c,0)c_Location_Qty
from #Stack10072017040904
pivot
(Sum(Qty) for Location in ([a],[b],c) )pvt
drop table #Stack10072017040904
Try this Dynamic Sql
Declare
#Sql nvarchar(max),
#dynamicCol nvarchar(max),
#dynamicCol2 nvarchar(max)
--Create columns Dynamically
SELECT #dynamicCol=STUFF((SELECT DISTINCT ', '+ QUOTENAME(Location )
From #Stack10072017040904 For XML PATH ('')),1,1,'')
SELECT #dynamicCol2=STUFF((SELECT DISTINCT ', '+ 'ISNULL ('+ QUOTENAME(Location )+ ','+'''0'''+')' +' AS '+Location+'_Location_Qty'
From #Stack10072017040904 For XML PATH ('')),1,1,'')
SET #Sql='
SELECT [Item_id] ,'+ #dynamicCol2 +' From
(
SELECT * From
#Stack10072017040904
)AS Src
PIVOT
(
MAX([Qty]) For [Location] IN ('+#dynamicCol+')
)
AS Pvt'
PRINT #Sql
EXEC(#Sql)
Result
Item_id a_Location_Qty b_Location_Qty c_Location_Qty
-------------------------------------------------------
1 1 3 0
2 0 2 2
3 1 0 3
Build columns dynamically and use a dynamic PIVOT:
Create Table #Test(Item_id varchar(100),Location varchar(100),Qty int)
insert into #Test values( '1','a','1')
insert into #Test values( '2','b','2')
insert into #Test values( '3','c','3')
insert into #Test values( '3','a','1')
insert into #Test values( '2','c','2')
insert into #Test values( '1','b','3')
DECLARE #cols1 AS NVARCHAR(MAX), #cols2 AS NVARCHAR(MAX), #query AS NVARCHAR(MAX);
SET #cols1 = STUFF((SELECT distinct ', isnull(' + quotename(s.Location) + ', 0) as ' + quotename(s.Location)
FROM #Test s
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #cols2 = STUFF((SELECT distinct ',' + quotename(s.Location)
FROM #Test s
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Item_id, ' + #cols1 + ' from
(
select Item_id
, Location
, Qty
from #Test
) x
pivot
(
max(qty)
for Location in (' + #cols2 + ')
) p '
execute(#query)
drop table #Test
I have a table like this:
id unit
1 mm
2 cm
3 kg
When I perform pivot operation on this, I am getting result as follows:
1 2 3
mm cm kg
Is it possible to get custom column names here, something like this:
d1 d2 d3
mm cm kg
I am using Pivot for this as:
IF OBJECT_ID('tempdb..#t') IS NOT NULL
DROP TABLE #t
GO
CREATE table #t
(id varchar(max),unit varchar(max))
insert into #t (id,unit)values
(1,'kg'),
(2,'cm'),
(3,'mm'),
(4,'m')
DECLARE #statement NVARCHAR(max)
,#columns NVARCHAR(max)
SELECT #columns = ISNULL(#columns + ',', '') + N'[' + cast(tbl.id as varchar(max)) + ']'
FROM (
SELECT DISTINCT id
FROM #t
) AS tbl
SELECT #statement = 'select *
INTO ##temp
from (
SELECT id,[unit]
FROM #t
) as s
PIVOT
(max(unit) FOR id in(' + #columns + ')) as pvt
'
EXEC sp_executesql #statement = #statement
SELECT * FROM ##temp
DROP TABLE #t
DROP TABLE ##temp
Is it possible?
Thanks
IF OBJECT_ID('tempdb..#t') IS NOT NULL
DROP TABLE #t
GO
CREATE TABLE #t (
id VARCHAR(10),
unit VARCHAR(100)
)
INSERT INTO #t (id, unit)
VALUES
('1', 'kg'),
('2', 'cm'),
('3', 'mm'),
('4', 'mm')
DECLARE #SQL NVARCHAR(MAX), #columns NVARCHAR(MAX)
SELECT #columns = STUFF((
SELECT ',[D' + id + ']'
FROM #t
FOR XML PATH('')), 1, 1, '')
SELECT #SQL = '
SELECT *
FROM (
SELECT [unit], col = N''D'' + id
FROM #t
) s
PIVOT (MAX(unit) FOR col IN (' + #columns + ')) p'
EXEC sys.sp_executesql #SQL
Just add a prefix to your ID. Example
SELECT #statement = 'select * INTO ##temp from
( SELECT [id] = ''d''+id,[unit] FROM #t ) as s
PIVOT
(max(unit) FOR id in(' + #columns + ')) as pvt '
Also it's terrible practice to use global temp tables! Especially one named ##temp
You can use a CASE expression with a dynamic sql query.
CREATE TABLE #t
(
id INT,
unit VARCHAR(2)
);
INSERT INTO #t VALUES
(1,'mm'),
(2,'cm'),
(3,'kg');
DECLARE #query AS VARCHAR(MAX);
SELECT #query = 'SELECT ' +
STUFF
(
(
SELECT DISTINCT ',MAX(CASE WHEN id = '+ CAST(id AS VARCHAR(10))
+ ' THEN unit END) AS d' + CAST(id AS VARCHAR(10))
FROM #t
FOR XML PATH('')
),
1,1,'');
SELECT #query += ' FROM #t;';
EXECUTE(#query);
Result
+----+----+----+
| d1 | d2 | d3 |
+----+----+----+
| mm | cm | kg |
+----+----+----+
SELECT #statement = 'select * INTO ##temp from ( SELECT ''d''+id AS [id],[unit] FROM #t ) as s PIVOT (max(unit) FOR id in(' + #columns + ')) as pvt '
I've just started learning SQL and am struggling with dynamically transposing a three column table correctly. I previously hard coded the query, but now need it to be dynamic as the values in my pivot column may change in the future.
Here's my starting point:
questionid | DebriefingQuestionResults | OperationSessionRecordID
------------------------------------------------------------------
32 | 3 | 8071
34 | 0 | 8071
36 | 1 | 8071
32 | 2 | 8074
34 | 6 | 8074
36 | 5 | 8074
And here's what I want to produce:
OperationSessionRecordID | 32 | 34 | 36
----------------------------------------------
8071 | 3 | 0 | 1
8074 | 2 | 6 | 5
There are only three [questionid] values (32, 34, and 36), at the moment but this may change in the future, hence wanting a dynamic query. There are about 12000 [OperationSessionRecordID] values. All columns are of the type int not null.
Based on this answer I've got this so far, but am not sure how to proceed as it throws the error shown below.
USE training_db
--Test to see if table exists, if so drop ready for creation--
IF OBJECT_ID('TheatreMan.DebriefingQuestionsResultsPivoted','U') IS NOT NULL
DROP TABLE TheatreMan.DebriefingQuestionsResultsPivoted
--Declare query and variable names--
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get Distinct values of the PIVOT column--
SET #ColumnName = STUFF((SELECT DISTINCT ',' + QUOTENAME(c.questionid)
FROM dbo.DebriefingQuestionsResultsTEMP
FOR XML PATH (''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
'SELECT OperationSessionRecordID, ' + #ColumnName + '
(select questionid,
DebriefingQuestionResults
OperationSessionRecordID
FROM dbo.DebriefingQuestionsResultsTEMP)
x
PIVOT (
min(DebriefingQuestionResults)
for questionid in (' + #ColumnName + ')
)
AS PIV'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
When I run this it throws this error, so something's obviously wrong with my #ColumnName variable, but I can't work out what it is.
Msg 4104, Level 16, State 1, Line 9
The multi-part identifier "c.questionid" could not be bound.
Any help would be most appreciated!
SB
This should work:
declare #collist nvarchar(max)
SET #collist = stuff((select distinct ',' + QUOTENAME(questionid)
FROM #t -- your table here
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
declare #q nvarchar(max)
set #q = '
select OperationSessionRecordID, ' + #collist + '
from (
select OperationSessionRecordID, DebriefingQuestionResults, questionid
from (
select *
from #t -- your table here
) as x
) as source
pivot (
sum(DebriefingQuestionResults)
for questionid in (' + #collist + ')
) as pvt
'
exec (#q)
try this, I think you just misspelled variable name.
USE training_db
--Test to see if table exists, if so drop ready for creation--
IF OBJECT_ID('TheatreMan.DebriefingQuestionsResultsPivoted','U') IS NOT NULL
DROP TABLE TheatreMan.DebriefingQuestionsResultsPivoted
--Declare query and variable names--
DECLARE # USE training_db
--Test to see if table exists, if so drop ready for creation--
IF OBJECT_ID('TheatreMan.DebriefingQuestionsResultsPivoted','U') IS NOT NULL
DROP TABLE TheatreMan.DebriefingQuestionsResultsPivoted
--Declare query and variable names--
DECLARE #QuestionPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get Distinct values of the PIVOT column--
SET #ColumnName = STUFF((SELECT DISTINCT ',' + QUOTENAME(c.questionid)
FROM dbo.DebriefingQuestionsResultsTEMP
FOR XML PATH (''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
'SELECT OperationSessionRecordID, ' + #ColumnName + '
(select questionid,
DebriefingQuestionResults
OperationSessionRecordID
FROM dbo.DebriefingQuestionsResultsTEMP
ORDER BY OperationSessionRecordID ASC
)x
PIVOT
(
min(DebriefingQuestionResults)
for questionid in (' + #ColumnName + ')
)
AS PIV'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get Distinct values of the PIVOT column--
SET #ColumnName = STUFF((SELECT DISTINCT ',' + QUOTENAME(c.questionid)
FROM dbo.DebriefingQuestionsResultsTEMP
FOR XML PATH (''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
'SELECT OperationSessionRecordID, ' + #ColumnName + '
(select questionid,
DebriefingQuestionResults
OperationSessionRecordID
FROM dbo.DebriefingQuestionsResultsTEMP)
x
PIVOT (
min(DebriefingQuestionResults)
for questionid in (' + #ColumnName + ')
)
AS PIV'
ORDER BY OperationSessionRecordID ASC
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
I have a table( in SQL Server 2008) which has vertical sales transactions data, i would like to convert vertical output to horizontal output, i tried to use PIVOT, but some how not getting idea how to apply group by on PIVOT, as i want Sum based on AccountHeadID, TransType and IsPast Column.
Sample Table
CREATE TABLE Trans
([TransID] int,
[CustID] int,
[AccountHeadID] int,
[TransType] varchar(100),
[IsPast] bit,
[Amount] int)
;
INSERT INTO Trans
([TransID],CustID, [AccountHeadID], [TransType], [IsPast],[Amount])
VALUES
(1, 1, 1, 'Sales',1,1000),
(2, 1, 1, 'Sales',0,500),
(3, 1, 1, 'Sales',0,400),
(4, 1, 1, 'Return',0,300),
(5, 1, 1, 'Return',0,200),
(6, 1, 1, 'Return',0,100),
(7, 1, 1, 'Return',1,150),
(8, 1, 2, 'Sales',1,2000)
Current Query
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(AccountHeadID)
from Trans
group by AccountHeadID
order by AccountHeadID
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT CustID,' + #cols + '
from
(
SELECT
a.CustID,
a.AccountHeadID,
a.TransType,
a.Amount,
a.isPast
FROM Trans a
) x
pivot
(
sum(Amount)
for AccountHeadID in (' + #cols + ')
) p '
execute sp_executesql #query;
Expected Output
CustID | Account-HeadID-TransType-IsPast[1-Sales-Past] | Account-HeadID-TransType-IsCurrent[1-Sales-Current] | Account-HeadID-TransType-IsCurrent[1-Return-Past] | Account-HeadID-TransType-IsCurrent[1-Return-Current] | Account-HeadID-TransType-IsCurrent[2-Sales-Past]| ...
1 |1000 | 900 (500 + 400) |150 | 600[300+200+100] |2000
See SQL Fiddle with Demo
Any suggestion or input are most welcome!
Thanks
Suresh
Try this:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(CONVERT(NVARCHAR(10),AccountHeadID) + N'-' + TransType + N'-' + CONVERT(NVARCHAR(10),IsPast))
from Trans
group by AccountHeadID, TransType, IsPast
order by AccountHeadID, TransType, IsPast
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--select #cols
set #query = 'SELECT CustID,' + #cols + '
from
(
SELECT
a.CustID,
CONVERT(NVARCHAR(10),AccountHeadID) + N''-'' + TransType + N''-'' + CONVERT(NVARCHAR(10),IsPast) Acct,
a.Amount
FROM Trans a
) x
pivot
(
sum(Amount)
for Acct in (' + #cols + ')
) p '
execute sp_executesql #query;
SQL Fiddle