473,698 Members | 2,628 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

1:m database relation "Flattened" for reporting purposes

--
Example Schema posted at end of message:
---
For reporting purposes, I need to build a single comma delimited string of
values from the "many" table
of a database.

The easiest way to see what I want is to look at the sample after my
signature.
By the way, this is actually a busines problem, not homework! I just
created a simple
example using class and persons because everyone is familiar with that
relationship.

I have two tables on the 'one' side of the relationship: PERSON and CLASS
The ENROLLMENT table resolves the many to many relationship between PERSON
and CLASS.
(I know that a real system would be date effective, etc, but this is just a
simple example.
that will show my problem). ENROLLMENT has one row for each Class in which a
Person is enrolled.

Look at the sample report: I have to "flatten" the join result and list
the class titles in a
comma delimited string. I am stuck with this reporting requirement, and I
am NOT going to denormalize
the tables.

One way to accomplish the result is to use a cursor to step through the rows
and build a "Classes"
string with concatenation. I don't much like this option. I am not writing
the front end code,
but I want to make it easy for the developer. Ideally, I would like to give
him a flattened view
so he can just do a simple join and run his report.

I believe that what I want cannot be accomplished with ANSI SQL. However,
does MS SQL have some
extensions that could help me do the job? Failing that, how could I write a
stored procedure that would
return the personID and the "Classes" string in a format that would be
joinable to the other tables?
Thanks,
Bill MacLean

P.S. Some people like to see actual database scripts as samples instead of
a textual representation.
I have pasted in a script that creates sample tables and populates them.

--Sample Tables and Reports:
TABLE PERSON
PersonID LastNM FirstNM
--------- ----------- ---------
1 Smith John
2 Jones Sara
3 Smith Lucille
TABLE CLASS
ClassID ClassNM
----------- ------------------
10 SQL Server 101
20 C++
25 Object Oriented Design
40 Inorganic Chemistry
50 Organic Chemistry
80 Early Lit.

TABLE ENROLLMENT
PersonID ClassID
-------- ---------
1 10
2 10
1 40
1 80
3 20
3 25

SAMPLE REPORT
Person ID Name Classes
--------- ----------------------- ------------------------------------
-----------------------------
1 Smith, John SQL Server 101, Inorganic Chemistry,
Early Lit.
2 Jones, Sara SQL Server 101
3 Smith, Lucille C++, Object Oriented Design
/*************** *************** *************** *************
SQL Server Script
/*************** *************** *************** *************/

CREATE TABLE [dbo].[CLASS] (
[ClassID] [int] NOT NULL ,
[ClassNM] [varchar] (25) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[ENROLLMENT] (
[PersonID] [int] NOT NULL ,
[ClassID] [int] NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[PERSON] (
[PersonID] [int] NOT NULL ,
[LastNM] [varchar] (25) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT NULL ,
[FirstNM] [varchar] (15) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[CLASS] WITH NOCHECK ADD
CONSTRAINT [PK_CLASS] PRIMARY KEY CLUSTERED
(
[ClassID]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[ENROLLMENT] WITH NOCHECK ADD
CONSTRAINT [PK_ENROLLMENT] PRIMARY KEY CLUSTERED
(
[PersonID],
[ClassID]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[PERSON] WITH NOCHECK ADD
CONSTRAINT [PK_PERSON] PRIMARY KEY CLUSTERED
(
[PersonID]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[ENROLLMENT] ADD
CONSTRAINT [FK_ENROLLMENT_C LASS] FOREIGN KEY
(
[ClassID]
) REFERENCES [dbo].[CLASS] (
[ClassID]
),
CONSTRAINT [FK_ENROLLMENT_P ERSON] FOREIGN KEY
(
[PersonID]
) REFERENCES [dbo].[PERSON] (
[PersonID]
)
GO

-- Insert rwo for each CLASS
INSERT INTO CLASS VALUES (10,'SQL Server 101');
INSERT INTO CLASS VALUES (20,'C++');
INSERT INTO CLASS VALUES (25,'Object Oriented Design');
INSERT INTO CLASS VALUES (40,'Inorganic Chemistry');
INSERT INTO CLASS VALUES (50,'Organic Chemistry');
INSERT INTO CLASS VALUES (80,'Early Lit.');

-- Insert row for each PERSON
INSERT INTO PERSON VALUES (1, 'Smitn','John') ;
INSERT INTO PERSON VALUES (2, 'Jones','Sara') ;
INSERT INTO PERSON VALUES (3, 'Smith','Lucill e');

--Insert row for each ENROLLMENT
INSERT INTO ENROLLMENT VALUES (1,10);
INSERT INTO ENROLLMENT VALUES (1,40);
INSERT INTO ENROLLMENT VALUES (1,80);
INSERT INTO ENROLLMENT VALUES (2,10);
INSERT INTO ENROLLMENT VALUES (3,20);
INSERT INTO ENROLLMENT VALUES (3,25);
Jul 20 '05 #1
3 2438
[posted and mailed, please reply in news]

Bill MacLean (bs**********@a tt.net) writes:
One way to accomplish the result is to use a cursor to step through the
rows and build a "Classes" string with concatenation. I don't much like
this option. I am not writing the front end code, but I want to make it
easy for the developer. Ideally, I would like to give him a flattened
view so he can just do a simple join and run his report.
Using a cursor is the only way you can to this in SQL Server reliably.
There exists a few tricks but they are not supported, and the result is not
always what you want.

From the point of view of effeciency it would be better to just select
the raw data, and do the formatting in client code.
Failing that, how could I write a stored procedure that would return the
personID and the "Classes" string in a format that would be joinable to
the other tables?


You could put the cursor thing in a table-valued function which you then
could join to other tables.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #2
You cannot do this directly. t-SQL resultsets returns tables with rows
having column, with each column representing a single value. So you will
have to hack up some kludge to get this done from the Server. Some such
ideas can be found at:
http://groups.google.com/groups?selm...TNGP09.phx.gbl

A more reliable approach is to return the resultset to the client
application & format or concatenate the way you want.

--
Anith
Jul 20 '05 #3
Thank you both Erland and Anith for the help. I really like method #4 on
the post that Anith linked. That method uses a table-valued function that
does not even use a cursor! The method appears to work great on the sample
Northwind database. I will adapt the idea to the dev environment for the
project here at work, and see how it scales.

I really like the idea of sparing the developers all the client side work,
so that function seems pretty neat. I'm still trying to figure out
exactly how it works, but I like the results.

Of course, I wish the concatenated output weren't necessary in the first
place, this appears to be a nice solution.

Thanks,

Bill
"Anith Sen" <an***@bizdatas olutions.com> wrote in message
news:y6******** ********@newsre ad1.news.pas.ea rthlink.net...
You cannot do this directly. t-SQL resultsets returns tables with rows
having column, with each column representing a single value. So you will
have to hack up some kludge to get this done from the Server. Some such
ideas can be found at:
http://groups.google.com/groups?selm...TNGP09.phx.gbl
A more reliable approach is to return the resultset to the client
application & format or concatenate the way you want.

--
Anith

Jul 20 '05 #4

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

Similar topics

11
14253
by: Nicolas Girard | last post by:
Hi, Forgive me if the answer is trivial, but could you tell me how to achieve the following: {k1:,k2:v3,...} --> ,,,...] The subtle point (at least to me) is to "flatten" values that are lists. Thanks in advance,
33
9164
by: Jim Hill | last post by:
I've done some Googling around on this and it seems like creating a here document is a bit tricky with Python. Trivial via triple-quoted strings if there's no need for variable interpolation but requiring a long, long formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my question is: Is there a way to produce a very long multiline string of output with variables' values inserted without having to resort to this wacky """v...
4
1506
by: Yannick Turgeon | last post by:
Hello all, I'm using SS 2000 and NT4. Say I've got three tables: T1, T2 and T3. T3 contains the 1-to-multiple data of the relation between T1 and T2: ------------------------------------------------ CREATE TABLE #T1( T1PK INTEGER NOT NULL PRIMARY KEY,
0
1182
by: sjallard | last post by:
Dear all, This is my first work with the XML extenders: I'll have to decompose an XML file into a DB2 table, and "flatten" it in the same time, like in the example at the end of this message. I need to do that on an iSeries with XML Extenders V4R5, but plan to test it first on a Windows installation (DB2 Express, from the DB2 on Rails installation http://alphaworks.ibm.com/tech/db2onrails/download).
8
3284
by: Good Man | last post by:
Hi there We've found a fantastic solution for generating PDF documents with fairly complex XHTML and CSS. It does a great job (on all our tests so far...) It's called "Prince" ( http://www.princexml.com/overview/ ) and the only thing holding me back is the server license fee - US $3,800. Has anyone used Prince? How do you like it? Worth the money spent?
0
1436
by: smitty1e | last post by:
Disclaimer(s): the author is nobody's pythonista. This could probably be done more elegantly. The driver for the effort is to get PyMacs to work with new-style classes. This rendering stage stands alone, and might be used for other purposes. A subsequent post will show using the resulting file to produce (I think valid) .el trampoline signatures for PyMacs. If nothing else, it shows some python internals in an interesting way.
26
1848
by: Frank Samuelson | last post by:
I love Python, and it is one of my 2 favorite languages. I would suggest that Python steal some aspects of the S language. ------------------------------------------------------- 1. Currently in Python def foo(x,y): ... assigns the name foo to a function object. Is this pythonic? Why not use the = operator like most other assignments?
0
8609
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
9170
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
9031
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
8901
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,...
1
6528
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
4371
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
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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
2
2336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.