Solved

Pivot/Unpivot master detail?

Posted on 2013-07-01
2
671 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
2 Comments
 
LVL 35

Accepted Solution

by:
David Todd earned 500 total points
Comment Utility
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 59

Expert Comment

by:Kevin Cross
Comment Utility
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Join & Write a Comment

'Between' is such a common word we rarely think about it but in SQL it has a very specific definition we should be aware of. While most database vendors will have their own unique phrases to describe it (see references at end) the concept in common …
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.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

743 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

22 Experts available now in Live!

Get 1:1 Help Now