Solved

Pivot/Unpivot master detail?

Posted on 2013-07-01
2
685 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
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 59

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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Suggested Solutions

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

839 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