One way would be to use a CTE for the output from your initial query (e.g. see
Common Table Expressions(CTE) in SQL SERVER 2008[
^])
You can then pivot the results (e.g. see
Simple Way To Use Pivot In SQL Query[
^])
One problem I didn't understand is where you got the column names from (
[0]
,
[1]
etc)
The following works with the data you have shown, but I'm not convinced it's what you're actually after ... for example are there really only 3 possible values of ParsedValue and if not what are you expecting the criteria for appearing in each column to be?
;with CTE as
(
select StockId,Convert(int,IsNull(PurUnit.ParsedValue,0))ParsedValue
from StockDetails CROSS APPLY fn_split_inline_cte(StockDetails.TspNo,',') PurUnit
)
SELECT StockId, [4] AS [0], [10] AS [1], [11] AS [2]
FROM (
SELECT ParsedValue,StockId
FROM CTE
) as sourceData
PIVOT
(
MAX(ParsedValue)
FOR ParsedValue IN ([4], [10], [11])
)AS pivotData
[EDIT - if those columns [0],[1],[2] are supposed to represent the Rank of the values for each StockId - i.e. top 3 values for each stockid, then try the following
;with CTE as
(
select StockId,Convert(int,IsNull(PurUnit.ParsedValue,0))ParsedValue
from StockDetails CROSS APPLY fn_split_inline_cte(StockDetails.TspNo,',') PurUnit
)
SELECT *
FROM
(
select
Rank() over (Partition by StockId Order by ParsedValue) - 1 as ranks,
StockId, ParsedValue
from CTE
) as sourceData
PIVOT
(
MAX(ParsedValue)
FOR ranks IN ([0], [1], [2])
)AS pivotData