473,781 Members | 2,280 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting data from multiple rows into one column

I have a table that has values as follows:
PersonID Degree
55 MD
55 Phd
55 RN
60 MD
60 Phd

I need a create a query that will give me output like this:

PersonID Degree
55 MD, Phd, RN
60 MD, Phd

Any ideas

Dec 3 '05 #1
16 43357
bika (ae*****@gmail. com) writes:
I have a table that has values as follows:
PersonID Degree
55 MD
55 Phd
55 RN
60 MD
60 Phd

I need a create a query that will give me output like this:

PersonID Degree
55 MD, Phd, RN
60 MD, Phd


If you are on SQL 2000, you will have to run a cursor. There is no defined
way to produce this result set. (There are some undefined ways which may
work, but I would not recommend to rely on.)

If you are on SQL 2005, this is possible thanks to the improved XML support.
I got this example from an SQL Server developer:

select CustomerID,
substring(OrdId List, 1, datalength(OrdI dList)/2 - 1)
-- strip the last ',' from the list
from
Customers c cross apply
(select convert(nvarcha r(30), OrderID) + ',' as [text()]
from Orders o
where o.CustomerID = c.CustomerID
order by o.OrderID
for xml path('')) as Dummy(OrdIdList )
go

I have not really grasped how it works, but it works. :-)

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

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Dec 3 '05 #2
Here's another one:

If you know in advance what the different types of degrees are going to
be you can use this query:

select personid,
Min(Case when Degree = 'Md' then degree end) as 'Md',
Min(Case when Degree = 'Phd' then degree end) as 'Phd',
Min(Case when Degree = 'Rn' then degree end) as 'Rn'
from Degrees
group by PersonId

If you dont know in advance what degrees you can expect in the db, you
can use a cursor to produce the 'min(case ... end) as .., ' parts on
the fly:

declare @DegName varchar(50)
declare @Sql nvarchar(4000)

declare c cursor FAST_FORWARD for
select distinct degree from degrees order by degree

open c
fetch next from c into @DegName

set @Sql = 'select personid '
while @@Fetch_Status = 0
begin
set @Sql = @Sql + ', Min(Case when Degree = ''' + @DegName + ''' then
degree end) as ''' + @DegName + ''' '
fetch next from c into @DegName
end
close c
deallocate c
set @Sql = @Sql + ' from Degrees group by PersonId'
print @sql
exec (@sql)

Erland, i actually learned this dynamic sql from you!

Hope this helps,

Gert-Jan

Dec 3 '05 #3
This problem pops up a lot in database newsgroups. If you remember, rule 1
is "no repeating groups". So to create a query that creates repeating groups
goes against the SQL model.

To do this in the most SQL way, Create a table like
CREATE TABLE PersonDegrees(
PersonID int,
IsRN char(1),
Is MD char(1),
IsPHD char(1),
....
....
IsLawyer Char(1))

Where Is...= 'Y' or 'N'

This looks likes a repeatng group, but it is not.

This way you can do queries like:
Show me people that are MDs, PHDs, and not Lawyers.

You can easily populate this table from your original M:M table.

Rich
"bika" <ae*****@gmail. com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
I have a table that has values as follows:
PersonID Degree
55 MD
55 Phd
55 RN
60 MD
60 Phd

I need a create a query that will give me output like this:

PersonID Degree
55 MD, Phd, RN
60 MD, Phd

Any ideas

Dec 4 '05 #4
Could you explain why you want to violate

1) The foundation of RDBMS, First Normal Form?
2) The most basic rule of a tiered architecture?

If you have a solid reason, woudl you mind publishing it, since that
would overturn 30+ yers of RDBMS and 40+ years of Comp Sci.

Dec 4 '05 #5
--CELKO-- (jc*******@eart hlink.net) writes:
Could you explain why you want to violate

1) The foundation of RDBMS, First Normal Form?
Because that is the way the user wants to see the data. You know plain
users does not give a dim wit about first normal forms. For them a
presentation like:

A: 2, 1, 2, 3
B: 3, 4, 5, 3

is probably a very normal form to them.
2) The most basic rule of a tiered architecture?
While this is best done client-side with SQL 2000, I don't think this is
something which is very well supported with report writers. And not all
clients are even that sophisticated. Many reports are run from Query
Analyzer or a similar tool with no formatting capabilities at all. Thus,
any formatting has to be done in the RBDMS.
If you have a solid reason, woudl you mind publishing it, since that
would overturn 30+ yers of RDBMS and 40+ years of Comp Sci.


Incidently, I have told you this several times before. So why do you keep
asking questions, when you do not listen to the answers?
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Dec 4 '05 #6
> The most basic rule of a tiered architecture?

The most basic rule of business is making money. Soemtimes it is way
cheaper to implement formatting just once in the database, as opposed
to doing it in VB, Crystal report, ASP, ASP.Net, whatever else.

Also note that data is transferred to the client in packets. So the
difference between sending over the network 1 packet:

Smith, John 1,3,5,7,17

and sending over the network 2 or more packets:

Smith, John 1
Smith, John 3
Smith, John 5
Smith, John 7
Smith, John 17

is at least 100% drop in performance.

Dec 4 '05 #7
Joe, I'm with you on this one. These young gunners seem to think of RDMS as
a file access mechanism. Just read the MYSQL Newsgroup. BTW I'm about your
age.
"--CELKO--" <jc*******@eart hlink.net> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
Could you explain why you want to violate

1) The foundation of RDBMS, First Normal Form?
2) The most basic rule of a tiered architecture?

If you have a solid reason, woudl you mind publishing it, since that
would overturn 30+ yers of RDBMS and 40+ years of Comp Sci.

Dec 4 '05 #8
But you notice in this example the number of columns is fixed. Not what the
OP wanted.

Rich
"Erland Sommarskog" <es****@sommars kog.se> wrote in message
news:Xn******** **************@ 127.0.0.1...
--CELKO-- (jc*******@eart hlink.net) writes:
Could you explain why you want to violate

1) The foundation of RDBMS, First Normal Form?


Because that is the way the user wants to see the data. You know plain
users does not give a dim wit about first normal forms. For them a
presentation like:

A: 2, 1, 2, 3
B: 3, 4, 5, 3

is probably a very normal form to them.
2) The most basic rule of a tiered architecture?


While this is best done client-side with SQL 2000, I don't think this is
something which is very well supported with report writers. And not all
clients are even that sophisticated. Many reports are run from Query
Analyzer or a similar tool with no formatting capabilities at all. Thus,
any formatting has to be done in the RBDMS.
If you have a solid reason, woudl you mind publishing it, since that
would overturn 30+ yers of RDBMS and 40+ years of Comp Sci.


Incidently, I have told you this several times before. So why do you keep
asking questions, when you do not listen to the answers?
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx

Dec 5 '05 #9
Rich,

So you've never had a requirement as a developer to show a comma seperated
list on the screen, i've done a lot of CRM development and that requirement
is very frequent.

Concatenating on the server scales significantly better than passing back
all the rows to the client/middle tier.

In SQL Server 2005 we can do it in one very simple statement utilising FOR
XML extensions, this makes for less code, less complexity and the logic is
coded once in a central location - do you not agree that is good?

--
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"Rich Ryan" <ry****@sbcglob al.net> wrote in message
news:OI******** *********@newss vr19.news.prodi gy.com...
Joe, I'm with you on this one. These young gunners seem to think of RDMS
as
a file access mechanism. Just read the MYSQL Newsgroup. BTW I'm about your
age.
"--CELKO--" <jc*******@eart hlink.net> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
Could you explain why you want to violate

1) The foundation of RDBMS, First Normal Form?
2) The most basic rule of a tiered architecture?

If you have a solid reason, woudl you mind publishing it, since that
would overturn 30+ yers of RDBMS and 40+ years of Comp Sci.


Dec 5 '05 #10

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

Similar topics

17
4690
by: John Hunter | last post by:
I have a largish data set (1000 observations x 100 floating point variables), and some of the of the data are missing. I want to try a variety of clustering, neural network, etc, algorithms on the data, and to keep life simple I want to reduce the dimensions of the matrix so that I have no missing values, since not all the algorithms are able to handle them and there is sufficient redundancy in the variables that I can afford to lose...
15
3827
by: Philip Mette | last post by:
I am begginner at best so I hope someone that is better can help. I have a stored procedure that updates a view that I wrote using 2 cursors.(Kind of a Inner Loop) I wrote it this way Because I couldn't do it using reqular transact SQL. The problem is that this procedure is taking longer and longer to run. Up to 5 hours now! It is anaylizing about 30,000 records. I think partly because we add new records every month. The procedure...
1
1664
by: Yama | last post by:
Hi, I am really confused. I have created a strong typed dataset for Northwind database Customer table. Now I am loading it with a stream of XML (ADO style) with the following: Customers _cust = new Customers(); XmlTextReader xmlReader = new XmlTextReader(stream); stream.Position = 0;
2
23942
by: Joe | last post by:
Hi All, I am new to using the Access DB and I need some help if someone is able to give it to me. What I want to do is get the names of the columns of certain tables. Not the data in the table but the table column names. I've seen other posts that suggest using the SQL command DESCRIBE but I can't get it to work for some reason. Other posts have code samples but they're written in VB which I am not familiar with. I
6
2247
by: melanieab | last post by:
Hi, Easy question. It seems to me that I'm following the examples correctly, but apparently I'm not. I'm trying to retrieve the data from a row called "row" and a column called "File". This is what I have: (xFile is the int value in column File and tCat is the table) First I try: xFile = int.Parse((tCat.Rows).ToString()); Another example I found:
1
5291
by: Craig Banks | last post by:
If a row of data in a dataset has a lot of columns the row displaying the data in a datagrid will run way off the screen. What I'd like to do is display a row of data over several datagrid rows so the user doesn't have to scroll horizontally. Essentially, I want to wrap a datagrid row (not text in individual columns) with as much control as possible. Make sense? While this seems simple enough on the surface, I can't figure out how to do...
11
2250
by: Siv | last post by:
Hi, I seem to be having a problem with a DataAdapter against an Access database. My app deletes 3 records runs a da.update(dt) where dt is a data.Datatable. I then proceed to update a list to reflect that the 3 items have been deleted only to discover that the 3 items appear, however when I click on them to display their information which runs a datareader over the same database it appears that the data has now gone. I wondered whether...
4
6019
by: Sean Shanny | last post by:
To all, Running into an out of memory error on our data warehouse server. This occurs only with our data from the 'September' section of a large fact table. The exact same query running over data from August or any prior month for that matter works fine which is why this is so weird. Note that June 2004 through today is stored in the same f_pageviews table. Nothing has changed on the server in the last couple of months. I upgraded...
6
2726
by: sgottenyc | last post by:
Hello, If you could assist me with the following situation, I would be very grateful. I have a table of data retrieved from database displayed on screen. To each row of data, I have added action buttons, such as "Edit", "Add", and "Comment". Since I do not know how many rows of data will be retrieved - and therefore how many buttons I need - I am using button arrays for each button, like so: echo "<input type=\"submit\"...
6
2945
by: insirawali | last post by:
Hi all, I have this problem, i need to know is there a way i cn use the data adapter's update method in this scenario. i have 3 tables as below create table table1{ id1 int identity(1,1) Constraint pk_table1 Primary Key,
0
9636
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
9474
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
10306
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10139
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...
1
10075
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8961
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...
1
7485
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6727
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();...
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.