Solved

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

Posted on 2008-06-18
5
4,523 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

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

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

738 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