Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to pivot the below table
Language Value
English En-text
France Fr-text
Arabic Ar-text

I want to result to be in the form
En-text Fr-text Ar-text
English France Arabic

How can I use pivot and do this? Note: Column has “-“ in value field….I don’t want to hardcode column names…if there are two more rows then it should take that value also ie: IN(slect * from Value)
Posted
Comments
syed shanu 15-Sep-14 2:08am    
Chk my article for the Pivot hope that will help you.in your case you can split the name by Space and create pivot.
http://www.codeproject.com/Articles/818756/Basic-SQL-Queries-for-Beginners#13
Member 11074115 15-Sep-14 2:31am    
I have written below query

select Value,Language from(
select Value,Language from [dbo].[getLabelValue1]
) up PIVOT
(SUM(Value) FOR Language IN(select Language from [dbo].[getLabelValue1)) as pvt

but it is throwing error after IN. It s not allowing query. Could you please correct my query

1 solution

Hi Check this i have worked out for you.

-- First Create sample table and insert your sample data
SQL
CREATE TABLE [dbo].[getLabelValue1](
	[Language] [varchar](20) NULL,
	[Value] [varchar](20) NULL
) ON [PRIMARY]
GO
INSERT INTO [TestTB].[dbo].[getLabelValue1]
           ([Language]
           ,[Value])
     VALUES
           ('English'
           ,'En-text')
           
           INSERT INTO [TestTB].[dbo].[getLabelValue1]
           ([Language]
           ,[Value])
     VALUES
           ('France'
           ,'Fr-text')
           
           INSERT INTO [TestTB].[dbo].[getLabelValue1]
           ([Language]
           ,[Value])
     VALUES
           ('Arabic'
           ,'Ar-text')
GO

Now run this pivot query.
SQL
DECLARE @MyColumns AS NVARCHAR(MAX),
    @SQLquery  AS NVARCHAR(MAX)
-- here first we get all the ItemName which should be display in Columns we use this in our necxt pivot query
select @MyColumns = STUFF((SELECT ',' + QUOTENAME(Language) 
                    from [getLabelValue1]
                    group by Language
                    order by Language
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
-- here we use the above all Item name to disoplay its price as column and row display
set @SQLquery = N'SELECT ' + @MyColumns + N' from 
             (
                 SELECT 
       Language, 
        Value as NewValues 
    FROM [getLabelValue1]
            ) x
            pivot 
            (
                 MAX(NewValues)
                for Language in (' + @MyColumns + N')
            ) p '
exec sp_executesql @SQLquery;
 
Share this answer
 

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