0

I am having some trouble with the next situation: I need to select 4 position for a statement and I need this positions to be pivoted as columns. The database is structured as: StatementId 1, PositionId 2, RepCurrValue 3. For example for StatementId = 55 and for the positions = 58 OR 62 OR 67 OR 82 the result is:

1   2   3
-----------------
55  58  146,8000
55  62  59,9800
55  67  800,0500
55  82  136,7600

and I want it to be

1  58       62      67       82
---------------------------------------
55 146,8000 59,9800 800,0500 136,7600

Thank you very much for your support.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Code_Noob
  • 77
  • 2
  • 7

1 Answers1

0

I did this exercise with PIVOT table that could be help you, considering the column headings equal to the contents of the field [2] and NOT providing repeated values ​​in column [2]:

DECLARE @cols AS NVARCHAR(MAX)

SET @cols =  STUFF((SELECT ',[' + convert(nvarchar,(t.[2])) + ']'  AS ID
 FROM TB_1 t
  FOR XML PATH(''), TYPE).value('.', 'varchar(max)'),1,1, '')

DECLARE  @query  AS NVARCHAR(MAX);  

SET @query = N'SELECT p.[1],' + @cols + N' from 
             (
                SELECT [1],[2],[3] FROM TB_1
            ) x
            pivot 
            (
                max([3])
                for [2] in (' + @cols + N')
            ) p 

            '
exec sp_executesql @query;

below the result obtained by adding an additional StatementId (56) and new different positions (90,91) associated with StatementId (56)

1   58          62      67          82          90      91
55  146,8000    59,9800 800,0500    136,7600    NULL    NULL
56  NULL        NULL    NULL        NULL        185,74  185,74

a non-dynamic solution can be:

select *
from 
(
   SELECT [1],[2],[3] FROM TB_1 
) x
pivot
(
  max([3])
  for [2] in ([58] , [62] , [67] , [82] )
) p
ɐlǝx
  • 1,384
  • 2
  • 17
  • 22