Solved

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

Posted on 2008-06-18
5
4,511 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 150 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 100 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Excel conversion issue with Sql server 14 46
datetime in sql 6 23
SQL Select Statement 2 20
TSQL DateADD update Question 4 25
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

919 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now