Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2008-06-18
5
Medium Priority
?
4,532 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 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
What if you have to shut down the entire Citrix infrastructure for hardware maintenance, software upgrades or "the unknown"? I developed this plan for "the unknown" and hope that it helps you as well. This article explains how to properly shut down …
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

721 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