Solved

Pivot/Unpivot master detail?

Posted on 2013-07-01
2
692 Views
Last Modified: 2013-07-12
Hello,

SQL Server 2008.

I have a master/detail relationship between two tables.  I need to write an export that returns the columns from the master table followed by the entries in the details table.

I guess i need to pivot/unpivot the details table?  The details table has two columns.  These are code and value.  However i dont know beforehand what the possible contents of code can be.

The output should look:

id,Name,Startdate,Code,Value,Code,Value,Code,Value,Code,Value,Code,Value,......

CREATE TABLE [dbo].[Master](
	[id] [int] NOT NULL,
	[Name] [varchar](50) NULL,
	[Startdate] [date] NULL)

CREATE TABLE [dbo].[Details](
	[id] [int] NOT NULL,
	[MasterId] [int] NULL,
	[Code] [nvarchar](20) NULL,
	[Value] [nvarchar](50) NULL)

Open in new window


Any ideas?
0
Comment
Question by:soozh
[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
2 Comments
 
LVL 35

Accepted Solution

by:
David Todd earned 500 total points
ID: 39291252
Hi,

A pivot operator isn't going to give you Code Value Code Value etc ...

it could give you value1 as Code1, value2 as Code2, value3 as Code3

See this:
use ExpertsExchange
go

set ansi_nulls on
set quoted_identifier on
set ansi_padding on
go

if exists (
	select * from sys.objects 
	where 
		object_id = OBJECT_ID( N'dbo.master' ) and type in ( N'U' )
	)
	drop table dbo.master
go

create table dbo.master (
	MasterID int identity not null
	, name varchar( 50 ) not null
	, startdate datetime null
	)
go

if exists (
	select * from sys.objects 
	where 
		object_id = OBJECT_ID( N'dbo.detail' ) and type in ( N'U' )
	)
	drop table dbo.detail
go

create table dbo.detail (
	DetailID int identity not null
	, MasterID int not null
	, code varchar( 20 ) null
	, charvalue varchar( 50 ) null
	, intvalue int null
	)
go

insert dbo.Master( name, startdate )
	values( 'Fred', dateadd( day, datediff( day, 0, getdate()), 0 ))
	, ( 'Jimmy', dateadd( day, datediff( day, 0, getdate()), 0 - 1 ))
;

go

insert dbo.detail( MasterID, code, intvalue )
	select 
		MasterID
		, 'something'
		, abs( checksum( newid())) % 100 
	from dbo.master

	union all

	select 
		MasterID
		, 'something else'
		, abs( checksum( newid())) % 100 
	from dbo.master


	union all

	select 
		MasterID
		, 'another thing'
		, abs( checksum( newid())) % 100 
	from dbo.master

go 100 -- 100 executions of this batch

select *
from dbo.master m
inner join dbo.detail d
	on d.MasterID = m.MasterID
;

select
	MasterID, Name, StartDate, [Something], [Something else], [another thing]
from (
	select 
		m.MasterID
		, m.name
		, m.startdate
		, d.code
		, d.intvalue
	from dbo.master m
	inner join dbo.detail d
		on d.MasterID = m.MasterID
	) p
	pivot (
		avg( p.intvalue )
	for code in (
		[Something]
		, [Something else]
		, [another thing]
		)
	) as pvt
;

Open in new window

http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

HTH
  David
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 39291885
An alternative would be to rank the code-value pairs based on the foreign key to the master table. Then derived tables, select codes and values independently with the rank as suffix. You can join the pivots to get code, value, code, value, ... this approach works with conditional aggregates versus pivots also if there is a fixed maximum number of codes/values per master record.
0

Featured Post

Industry Leaders: 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

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
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…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

742 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