Click here to Skip to main content
15,888,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
SQL
select StockId,Convert(int,IsNull(PurUnit.ParsedValue,0))ParsedValue  from StockDetails CROSS APPLY fn_split_inline_cte(StockDetails.TspNo,',') PurUnit


StockId              ParsedValue
-----------          -----------
20859                4
20859                10
20859                11
22845                4
22845                10
22845                11


I want this output help needed
StockId              [0]          [1]              [2]
-----------          -----------  -----------      ----------- 
20859                4            10               11
22845                4            10               11
Posted

1 solution

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?

SQL
;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
SQL
;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
 
Share this answer
 
v2
Comments
Dipak Mandol 30-Nov-15 8:25am    
Thank u much. the 2nd one is working properly for me which I exactly needed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900