?
Solved

Pivot/Unpivot master detail?

Posted on 2013-07-01
2
Medium Priority
?
701 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 2000 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

The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

Question has a verified solution.

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

This post looks at MongoDB and MySQL, and covers high-level MongoDB strengths, weaknesses, features, and uses from the perspective of an SQL user.
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

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