473,770 Members | 2,630 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Query to tranform rows to column

Hi

Your help for the following query will be highly apprecaited. I've
wasted alot of time on it. Data definition is at the bottom.

Thanks

-----------------------------------
Business need: User selects answers for few questions. Answers are
presented in the form of radio buttons.

Questions Table:

=============== ====

QuestionID QuestionName

1 1.Rate your organization

2 10.Opportunity in your group

3 117.Effectivene ss

----------------------------------------

Answers Table:

==============

AnswerId AnswerName QuestionID

1 1.Best 1

2 2.Average 1

3 3.Wrose 1

4 1.Hardly Any 2

5 2.not too much 2

6 3.Average 2

7 4.Great Deal 2

8 1.Strong 3

9 2.Minor 3

10 3.Nothing 3

--------------------------------------------------------



Lets say User ABC answered below:

For Question 1, she chose '2.Average'

For Question 2: she left blank

FOr Quesiton 3: she chose '2.Minor'

And for user XYZ:

For Question 1, she let blank

For Question 2: she left blank

FOr Quesiton 3: she chose '3.Nothing'

Then the Results table will look like this:

Results Table:

===============

Resultsid QuestionID AnswerId User

1 1 2 ABC

2 3 9 ABC

3 3 10 XYZ
---------------------------------------------------



Desired Output:

===============

User 1 10 117
--- -- --- ----

ABC 2 2

XYZ 3

Explanation:

--> Show ALL distinct users on rows

--> show ALL distinct QuestionName on the columns BUT only display the
number before '.'

--> Show the chosen answer (answername) for each user but only display
the number before '.'

-------------------------------------------------------------------

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[Questions]') and OBJECTPROPERTY( id, N'IsUserTable')
= 1)

drop table [dbo].[Questions]

GO

CREATE TABLE [dbo].[Questions] (

[QuestionId] [int] IDENTITY (1, 1) NOT NULL ,

[QuestionName] [nvarchar] (1000) COLLATE
SQL_Latin1_Gene ral_CP1_CI_AS NULL

) ON [PRIMARY]

GO

-------------------------------

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[Answers]') and OBJECTPROPERTY( id, N'IsUserTable') =
1)

drop table [dbo].[Answers]

GO

CREATE TABLE [dbo].[Answers] (

[AnswerId] [int] IDENTITY (1, 1) NOT NULL ,

[AnswerName] [nvarchar] (150) COLLATE
SQL_Latin1_Gene ral_CP1_CI_AS NULL ,

[QuestionId] [int] NULL

) ON [PRIMARY]

GO

----------------------------------

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[Results]') and OBJECTPROPERTY( id, N'IsUserTable') =
1)

drop table [dbo].[Results]

GO

CREATE TABLE [dbo].[Results] (

[ResultId] [int] IDENTITY (1, 1) NOT NULL ,

[QuestionId] [int] NULL ,

[AnswerId] [int] NULL ,

[UserId] [nchar] (40) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS
NULL

) ON [PRIMARY]

GO

---------------------------------------------

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'1.Best' ,

1

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'2.Average' ,

1

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'3.Wrose' ,

1

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'1.Hardly Any' ,

2

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'2.not too much' ,

2

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'3.Average' ,

2

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'4.Great Deal' ,

2

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'1.Strong' ,

3

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'2.Minor' ,

3

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'3.Nothing' ,

3

)

go

-----------------------------

INSERT Questions (

QuestionName

)

VALUES (

'1.Rate your organization'

)

go



INSERT Questions (

QuestionName

)

VALUES (

'10.Opportunity in your group'
)

go

INSERT Questions (

QuestionName

)

VALUES (

'117.Effectiven ess'

)

go

------------------------------------

INSERT Results (

QuestionId ,

AnswerId ,

UserId

)

VALUES (

1 ,

2 ,

'ABC'

)

go

INSERT Results (

QuestionId ,

AnswerId ,

UserId

)

VALUES (

3 ,

9 ,

'ABC'

)

go

INSERT Results (

QuestionId ,

AnswerId ,

UserId

)

VALUES (

3 ,

10 ,

'XYZ'

)

go

Jul 23 '05 #1
2 1596
I could think of two ways of doing it:

select users.userid,
(select answerid from results where results.userid =
users.userid and questionid = 1) as answer1,
(select answerid from results where results.userid =
users.userid and questionid = 2) as answer2,
....
from (select distinct userid from results) as users
order by users.userid

or

select users.userid,
answer1.answeri d as answer1,
answer2.answeri d as answer2,
....
from (select distinct userid from results) as users
left outer join results answer1
on users.userid = answer1.userid
and answer1.answeri d = 1
left outer join results answer2
on users.userid = answer2.userid
and answer1.answeri d = 2
....
order by users.userid

--
David Rowland
Do you know what people are doing on your database server?
Find out with dbmonitor!
http://dbmonitor.tripod.com

Jul 23 '05 #2
[posted and mailed, please reply in news]

(mu*****@hotmai l.com) writes:
Your help for the following query will be highly apprecaited. I've
wasted alot of time on it. Data definition is at the bottom.
...
Desired Output:
============== =

User 1 10 117
--- -- --- ----
ABC 2 2
XYZ 3

SQL is not really well suited for type query, as the columns depend
on the data. You don't say so, but I assume that there can be
any number of questions. The usual recommendation for this sort of
crosstab queries is RAC, see http://www.rac4sql.net.

But since you provided scripts and tables, and everything else I usually
nag about, I felt compelled to provide a solution. This uses dynamic SQL.
For more information on dynamic SQL, see
http://www.sommarskog.se/dynamic_sql.html.
DECLARE @selectlist varchar(8000),
@selfjoin varchar(8000),
@alias varchar(10),
@elias varchar(10),
@idstr varchar(10),
@qnostr varchar(10)

-- Map id:s to the numbers before the dot.
CREATE TABLE #idmap(id int NOT NULL PRIMARY KEY,
qno smallint NOT NULL UNIQUE)

-- Help table to get all distinct users that appear.
CREATE TABLE #users (userid nchar(40) NOT NULL PRIMARY KEY)

-- Maps answers ids to numbers before the dot.
CREATE TABLE #answermap(id int NOT NULL PRIMARY KEY,
ansno smallint NOT NULL)

-- Fill Idmap
INSERT #idmap(id, qno)
SELECT QuestionId,
convert(smallin t,
substring(Quest ionName, 1, charindex('.', QuestionName) - 1))
FROM Questions

-- Fill answermap
INSERT #answermap(id, ansno)
SELECT AnswerId,
convert(smallin t,
substring(Answe rName, 1, charindex('.', AnswerName) - 1))
FROM Answers

-- And get all users.
INSERT #users (userid)
SELECT DISTINCT UserId FROM Results

-- We now start to build a dynamic SQL statement. We build in two parts:
-- the SELECT list and the FROM clause.
SELECT @selectlist = 'SELECT u.userid ',
@selfjoin = 'FROM #users u '

-- We have to iterate of the #idmap table to build it. For the query
-- we need the id as a string, and the question number must be in [],
-- since it will be used as an identifier.
DECLARE build_cur INSENSITIVE CURSOR FOR
SELECT ltrim(str(id)), '[' + ltrim(str(qno)) + ']'
FROM #idmap
ORDER BY qno
OPEN build_cur

WHILE 1 = 1
BEGIN
FETCH build_cur INTO @idstr, @qnostr
IF @@fetch_status <> 0
BREAK

-- We will need two alias for the Results and #answermap table,
-- which will appear once for each question.
SELECT @alias = 'a' + @idstr, @elias = 'e' + @idstr

-- Add this question's answers to the SELECT list.
SELECT @selectlist = @selectlist + ', ' + @qnostr + ' = ' +
@elias + '.ansno '

-- And augment the FROM clause with this question. We left-join to
-- Results, since answer may be NULL. We need to look up answer in
-- the answer-map to get the real id.
SELECT @selfjoin = @selfjoin + char(10) +
'LEFT JOIN (Results ' + @alias + ' JOIN #answermap ' + @elias +
' ON ' + @alias + '.AnswerId = ' + @elias + '.id) ' +
' ON u.userid = ' + @alias + '.UserId AND ' +
@alias + '.QuestionId = ' + @idstr
END
DEALLOCATE build_cur

-- Debug prints that show the actual query
PRINT @selectlist
PRINT @selfjoin

-- Run the beast!
EXEC (@selectlist + @selfjoin + ' ORDER BY u.userid')
go
DROP TABLE #users, #idmap, #answermap

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
89318
by: Lauren Quantrell | last post by:
In VBA, I constructed the following to update all records in tblmyTable with each records in tblmyTableTEMP having the same UniqueID: UPDATE tblMyTable RIGHT JOIN tblMyTableTEMP ON tblMyTable.UniqueID = tblMyTableTEMP.UniqueID SET tblMyTable.myField = tblMyTableTEMP.myField, tblMyTable.myField2 = tblMyTableTEMP.myField2,
7
12091
by: Egor Shipovalov | last post by:
I'm implementing paging through search results using cursors. Is there a better way to know total number of rows under a cursor than running a separate COUNT(*) query? I think PostgreSQL is bound to know this number after the first FETCH, isn't it? On a side note, why queries using LIMIT are SO terribly slow, compared to cursors and sometimes even ones without LIMIT? Shouldn't LIMIT be internally implemented using cursor mechanism then?...
1
2490
by: Alex Satrapa | last post by:
I have a table from which I'm trying to extract certain information. For historical reasons, we archive every action on a particular thing ('thing' is identified, funnily enough, by 'id'). So the only way to find out the current state of a particular combination of attributes is to "select distinct on (id, ...) ... order by date desc". In the examples below, I've taken real output from psql and done a global search/replace on various...
8
3271
by: Együd Csaba | last post by:
Hi All, how can I improve the query performance in the following situation: I have a big (4.5+ million rows) table. One query takes approx. 9 sec to finish resulting ~10000 rows. But if I run simultaneously 4 similar queries it takes nearly 5 minutes instead of 4 times 9 seconds or something near of that. here is a sample query: select mertido, fomeazon, ertektipus, mertertek from t_me30 where fomeazon in (select distinct fomeazon...
3
1520
by: Matthew Kramer | last post by:
How would be the best way to do this in Access? I have two tables. The first table has all the rows of data. The first column of this table has a country name, the second has a year and the third column is the data value. The second table is just a list of standard years ie. 1980, 1985, 1990, 1995). Is there a way to arrange a query so that all of the rows in table 1
6
1710
by: Rory Campbell-Lange | last post by:
The following query on some small datasets takes over a second to run. I'd be grateful for some help in understanding the explain output, and to remake the code. Looks like the sort is using up quite a bit of resources. I made an index on boards using columns "b.n_type, b.n_id, b.t_name" but the index was not recorded in explain analyze. (see "testindex" below). I am using PostgreSQL 7.4.2 on i386-pc-linux-gnu (Debian). The query is...
6
4849
by: jjturon | last post by:
Can anyone help me?? I am trying to pass a Select Query variable to a table using Dlookup and return the value to same select query but to another field. Ex. SalesManID SalesManName AT Alan Time
2
2936
by: Nenad Markovic | last post by:
Hi everybody, When executing a Crosstab Query I see only rows (defined in a row heading) that have values (defined in value field) in at least one column (defined as column headings). How can I make a Crosstab Query that shows all rows, regardless they have values in column headings. For instance, the result that I get now is like this
1
1295
by: Xeth Waxman | last post by:
Good afternoon, I have a bizarre question. When running the following query: select SomeColumnName from TableA where PK_TableA in (select PK_TableA from TableB) I get results. This should not be feasible, because the query within the in clause:
0
9602
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9439
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10071
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9882
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8905
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6690
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5326
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5467
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3987
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.