Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

TSQL - Select multiple rows into single row. (Master / detail tables)

Posted on 2008-06-18
5
Medium Priority
?
4,543 Views
Last Modified: 2010-04-21
I am trying to put together a query that summarises a month worth of items in a detail table and I'm struggling a bit.  Basically what I want to have at the end is:

      Item 1 - 15 - £10
      Item 2 - 1 - £12
      Covers deliveries 1232, 1234, 502.  Dates 01/01/2000, 01/02/2000, 01/02/2000

The item rows are easy, but I'm not sure how to put together that final row.  Tables being worked with are something like this:

      Summary Table:
      ID
      Total
      Date

      Detail Table:
      ID
      SummaryID
      DeliveryNumber
      DeliveryDate
      
I can do a simple select to return all detail rows required (SELECT [DeliveryNumber], [DeliveryDate] FROM [DetailTable] WHERE [SummaryID] = @SummaryID) but I need to get this into a single row and formatted as closely as I can to the sample above.

Any solutions?
0
Comment
Question by:Psychotext
5 Comments
 
LVL 7

Accepted Solution

by:
Chrisedebo earned 600 total points
ID: 21812079
This is a procedure I created to do something similar with notes to transfer them between two different database systems. I'm sure you can butcher it to your needs.

If you need any help understanding what it's doing give me a shout.
IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
      WHERE TABLE_NAME like 'grouped') drop table grouped;
GO
 
CREATE TABLE Grouped
(
	claim_cnt int NOT NULL, 
	claim_public_text_id int Not NULL, 
	text_line varchar(4000) NULL
)
GO
 
 
declare @NoteNumber int
declare @uid int
declare @NoteDate varchar(20)
declare @NoteText varchar(255)
 
 
declare groupconcat cursor for 
 
select claim_cnt, text_line from Claimnotes 
order by claim_cnt,claim_public_text_ID
 
open groupconcat
 
fetch next from groupconcat into @uid, @NoteText
 
set @NoteNumber = 0
 
while @@fetch_status = 0 
 
Begin
	
	if left(@notetext,1) = '[' 
		Begin
			set @notenumber = @notenumber + 1
			insert into grouped (claim_cnt,claim_public_text_id,text_Line) 
			values (@uid,@notenumber,rtrim(@NoteText) + char(13) + char(10))
		End
	Else
		Begin 
			update grouped set text_line = text_line + rtrim(@NoteText)
			where claim_cnt = @uid and claim_public_text_id = @notenumber
		end
 
	fetch next from groupconcat into @uid, @NoteText	
 
END
 
close groupconcat
deallocate groupconcat
 
 
select * from grouped

Open in new window

0
 
LVL 2

Assisted Solution

by:AntonyDN
AntonyDN earned 400 total points
ID: 21812543
Hi,

I had to do exactly the same thing for a report, so here's a cut down version of what I did. I had to return loads of rows, but you are passing an ID in, so you will only have one row returned, which as way easier. This code will get you the row you need - you should be able to adapt it for your needs pretty easily.
-- This sets up the tables like you suggest you have ....
DECLARE @DetailTable TABLE(
      ID INT IDENTITY (1,1), 
      SummaryID INT,
      DeliveryNumber INT, 
      DeliveryDate DATETIME
	)
 
INSERT @DetailTable VALUES (1, 1232, '2000-01-01')
INSERT @DetailTable VALUES (1, 1234, '2000-01-02')
INSERT @DetailTable VALUES (1, 502, '2000-01-02')
 
-- Another Summary ID
INSERT @DetailTable VALUES (2, 2232, '2000-01-03')
INSERT @DetailTable VALUES (2, 2234, '2000-01-04')
INSERT @DetailTable VALUES (2, 2502, '2000-01-04')
 
DECLARE @SummaryID INT
SET @SummaryID = 1
 
-------------------------------------------------------------------------------------------------
-- Here's the bit you need to use in your proc ....
	DECLARE @DeliveryNumber INT, @DeliveryDate DATETIME;
	-- The lines to output
	DECLARE @Deliveries VARCHAR(1000), @Dates VARCHAR(1000);
 
	DECLARE cu CURSOR FOR 
		SELECT [DeliveryNumber], [DeliveryDate] FROM @DetailTable WHERE [SummaryID] = @SummaryID;
 
		OPEN cu
 
		FETCH NEXT FROM cu INTO  @DeliveryNumber, @DeliveryDate ;
		-- First row ....
		SET @Deliveries = 'deliveries: ' + CONVERT(VARCHAR(10), @DeliveryNumber, 101);
		SET @Dates = 'Dates ' + CONVERT(VARCHAR(10), @DeliveryDate, 101);
 
		FETCH NEXT FROM cu INTO @DeliveryNumber, @DeliveryDate;
			WHILE @@FETCH_STATUS = 0 BEGIN
				SET @Deliveries = @Deliveries +', ' + CAST(@DeliveryNumber AS VARCHAR(5));
				SET @Dates = @Dates +', ' +  CONVERT(VARCHAR(10), @DeliveryDate, 101);
 
				FETCH NEXT FROM cu INTO @DeliveryNumber, @DeliveryDate;
			END;
 
		-- Return the row you need ....
		SELECT 'Covers ' + @Deliveries + '. ' +  @Dates;
 
	CLOSE cu;
	DEALLOCATE cu;

Open in new window

0
 
LVL 2

Author Comment

by:Psychotext
ID: 21812568
Thanks both... will have a look and post back.
0
 
LVL 2

Author Closing Comment

by:Psychotext
ID: 31468301
Both are excellent, thanks.  Have given points to both as Chrisedebo was first but AntonyDN tailored the example specifically to my needs.

Thanks again.
0
 

Expert Comment

by:pdms123456
ID: 22204752
Here's a little known technique that can be useful when flattening out row values from a column

Declare @v VARCHAR (1000)

SELECT @v = 'Covers Deliveries: '

select @v = @v + DeliveryNumber + ', ' FROM [Detail Table] WHERE SummaryID = etc
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Microsoft Access has a limit of 255 columns in a single table; SQL Server allows tables with over 255 columns, but reading that data is not necessarily simple.  The final solution for this task involved creating a custom text parser and then reading…
One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

782 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question