Solved

Pivot/Unpivot master detail?

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

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.

Question has a verified solution.

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

Hi all, It is important and often overlooked to understand “Database properties”. Often we see questions about "log files" or "where is the database" and one of the easiest ways to get general information about your database is to use “Database p…
This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

770 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