473,421 Members | 1,652 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,421 software developers and data experts.

How to convert rows into columns?

Hi SMART GUYS,

Please help me write a query. Actually I want to convert my rows into columns. Can anyone kindly give me the query to do it? My rows are about employees. There can be any number of employees (in the following table I have 3 employees ABC, EFG, WRI) with any number of records for each employee (there can be 20, 30 records each), but all employees have the same number of records (in the following table each employee has 3 records). My table is:


USERID Name Role Total
100 ABC 1 0
100 ABC 1 0
100 ABC 1 1
101 EFG 1 0
101 EFG 1 2
101 EFG 1 1
102 WRI 2 1
102 WRI 2 0
102 WRI 2 1

I want to convert the above table in the following form:

USERID Name Role Total1 Total2 Total3
100 ABC 1 0 0 1
101 EFG 1 0 2 1
102 WRI 2 1 0 1

Columns [USERID], [Name], [Role] are unique for each row but Column [Total] is dynamic (in above case, 3 [Total] Columns Total1, Total2, Total3) and depends on the number of records against each employee. If there were 30 records for each employee, the Column [Total] will be (Total1, Total2, Total3…Total30), I have mentioned above that all employees will have the same number of records.

I have even used the Pivot Operator in SQL Server 2005 but it always end up in an error about the syntax proceeding the PIVOT word. I just need a query with/without the PIVOT operator.

I look forward to your reply. I will be highly obliged.

Regards...
Sep 5 '06 #1
9 101408
i think this will help you..

table design for me is like this

table name is::CandidateTemp

id FieldName Value

1 email aaa
1 skill c
1 name AAAAA
2 email aaa
2 skill c,java
2 name AAAAA
5 email aaa
5 skill c
5 name GGGG
9 email iii
9 skill c,vb,java
9 name AAAA



and i want this format

id email skill name

1 aaa c AAAAA
2 aaa c,java AAAAA
5 aaa c GGGG
9 iii c,vb,java AAAA


Query for this is



select a.id as id, a.Value as email, b.Value as skill, c.Value as name from CandidateTemp a,CandidateTemp b,CandidateTemp c where a.id=b.id and b.id=c.id
and a.FieldName='email' and b.FieldName='skill' and c.FieldName='name'
Oct 30 '06 #2
scripto
143 100+
Hi SMART GUYS,

Regards...
This was a nice challenge - i created a new_employee table to hold the results.
here it is based on your specific requirements:

CREATE TABLE [dbo].[new_employees] (
[userid] [int] NOT NULL ,
[name] [varchar] (50) NOT NULL ,
[role] [int] NOT NULL
) ON [PRIMARY]
GO

-- backup your employees table first
alter table employees add [ID] int identity(1,1) not null
go

declare @max int, @min int
set @max = (select max(id) from employees)
set @min = (select min(id) from employees)

declare @totcols int, @counter int
set @totcols = (select count(*) from employees where userid = 100)
set @counter = 1

declare @str varchar(50)
declare @sqlStr nvarchar(255)


while @counter <= @totcols
begin
set @str = 'total'+ convert(varchar(5),@counter)

set @sqlStr = N'alter table new_employees add '+ @str + ' int null'
exec sp_executesql @sqlStr


set @counter = @counter + 1
set @str = ''
set @sqlStr = ''
end

insert into new_employees (USERID, Name, Role)
select distinct USERID, Name, Role from employees


while @min <= @max
begin
set @counter = 1
while @counter <= @totcols
begin
set @str = 'total'+ convert(varchar(5),@counter)

set @sqlStr = N'update new_employees set ' + @str + ' = (select total from employees where id = ' + convert(varchar(5),@min) + ')' +
' where userid = (select userid from employees where id = ' + convert(varchar(5),@min) + ')'
exec sp_executesql @sqlStr

set @counter = @counter + 1
set @min = @min + 1
set @str = ''
set @sqlStr = ''

end


end



select * from new_employees
Oct 31 '06 #3
I have a table "parameterData" look like this:

ParID TimeStamp Scale Value
1 8/9/2007 10:48:46 AM 10 1500
2 8/9/2007 10:48:46 AM 10 1610
3 8/9/2007 10:48:46 AM 10 1640
4 8/9/2007 10:48:46 AM 10 1580
5 8/9/2007 10:48:46 AM 0.1 219.2
6 8/9/2007 10:48:46 AM 0.1 332.6
7 8/9/2007 10:48:46 AM 0.1 219.3
8 8/9/2007 10:48:46 AM 0.1 257
1 8/9/2007 10:50:06 AM 10 1570
2 8/9/2007 10:50:06 AM 10 1700
3 8/9/2007 10:50:06 AM 10 1470
4 8/9/2007 10:50:06 AM 10 1570
5 8/9/2007 10:50:06 AM 0.1 219.6
6 8/9/2007 10:50:06 AM 0.1 332.6
7 8/9/2007 10:50:06 AM 0.1 219.2
8 8/9/2007 10:50:06 AM 0.1 257

Timestamp value for all-eight row (parID 1-8) is same
I want to have a table where column like this
TimeStamp 1 2 3 4 5 6 7 8


How do i do this?

thanx
Aug 9 '07 #4
Kamboj
1
Here is a Query:-
SELECT USERID,NAME,ROLE,MAX(DECODE(R,1,TOTAL)) TOT1,
MAX(DECODE(R,2,TOTAL)) TOT2,
MAX(DECODE(R,3,TOTAL)) TOT3
FROM (SELECT USERID,NAME,ROLE,TOTAL
,ROW_NUMBER() OVER(PARTITION BY USERID ORDER BY USERID) R
FROM T3)
GROUP BY USERID,NAME,ROLE

----------output----------------------------------------------------------------------------

USERID NAME ROLE TOT1 TOT2 TOT3
---------- ----- ---------- ---------- ---------- ----------
100 ABC 1 0 0 1
101 EFG 1 0 2 1
102 WRI 2 1 0 1
Feb 17 '08 #5
ck9663
2,878 Expert 2GB
If you're using SQL 2005, you're in luck. Try here

-- CK
Feb 17 '08 #6
PIVOT relational operator in sql server 2005 can be used to convert rows to columns

http://www.logiclabz.com/sql-server/...ing-pivot.aspx
May 29 '09 #7
Thanks a ton!
Nov 3 '10 #8
Simplest way to achieve this..

Expand|Select|Wrap|Line Numbers
  1. CREATE TABLE [dbo].[test10](
  2.     [custID] [int] NULL,
  3.     [Question] [varchar](50) NULL,
  4.     [answer] [varchar](20) NULL
  5. ) ON [PRIMARY]
  6.  
  7. GO
  8.  
  9. INSERT INTO test10 values(1000,    'AAA',    '1')
  10. INSERT INTO test10 values(1000,    'BBB',    '2')
  11. INSERT INTO test10 values(1000,    'CCC',    '3')
  12. INSERT INTO test10 values(1001,    'AAA',    '2')
  13. INSERT INTO test10 values(1001,    'BBB',    '3')
  14. INSERT INTO test10 values(1001,    'CCC',    '3')
  15. INSERT INTO test10 values(1000,    'DDD',    '6')
  16.  
  17. GO
  18.  
  19. Declare @t VARCHAR(10)
  20. Declare @A VARCHAR(1000)
  21. Declare @B VARCHAR(1000)
  22. set @A='SELECT CustID'
  23. SET @B='('
  24. SELECT @A=@A+',['+Question+'] as ' +Question,@B=@B+'['+Question+'],' FROM (SELECT DISTINCT QUESTION FROM TEST10) cur
  25. -- removing last ',' from both variables
  26. SET @B=SUBSTRING(@B,1,LEN(@B)-1)
  27. SET @A=@A+ + ' FROM (SELECT CustID, Answer, Question FROM test10) s  PIVOT (max(answer) FOR Question IN ' +@B+')) p ORDER BY [CUSTID]; '
  28. exec(@A);
Nov 3 '10 #9
see the following post for this. you can convert into as many columns needed based on the possible row values

http://blog.programmingsolution.net/...dynamic-query/
Mar 23 '11 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: helpful sql | last post by:
Hi all, I am using an HTML table control on my ASP.Net page. Now I need to change this table so that columns become rows and rows become column. Since the table is very complex with many controls...
1
by: blah1234 | last post by:
Is there anyway in DB2 to convert rows to columns? In other words, if I have the following table below... MemberID AccountNum ZipCode ------------------------------------ 1234 1...
1
by: Stan Sainte-Rose | last post by:
Oopps sorry for the previous post. As I said, I m trying to make a web custom control and I do know how I have to convert this part to for the render section In fact it may be a stupid...
0
by: helpful sql | last post by:
Hi all, I am using an HTML table control on my ASP.Net page. Now I need to change this table so that columns become rows and rows become column. Since the table is very complex with many controls...
0
by: Harry Haller | last post by:
The context is shown below in the getGames() method. I get errors on these lines: dtGames.Rows = (TimeSpan)dtGames.Rows; dtGames.Rows = (DayOfWeek)dtGames.Rows; because the playDate column...
5
by: manmit.walia | last post by:
Hello All, I am stuck on a conversion problem. I am trying to convert my application which is written in VB.NET to C# because the project I am working on currently is being written in C#. I tried...
3
by: italia | last post by:
I have a database with 2 columns and more than million rows. The first column is the id Example of the data (2 columns)- 04731 CRM 04731 CRM 04731 CRM 04731 RVB 04731 RVB
4
by: RICALJE | last post by:
Hi All, Could you help me in my problem in working on a project that imports excel file to a datatable the validation is to catch all null values in the excel file because it will should not allow...
9
by: myotheraccount | last post by:
Hello, Is there a way to convert a DataRow to a StringArray, without looping through all of the items of the DataRow? Basically, I'm trying to get the results of a query and put them into a...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.