Saturday, February 25, 2012

Pivot Transformation Editor

Why isn't there an editor for the Pivot Transformation? It is one of the most common transforms I use and the Advanced Editor is a pain in the rear.

Is there a friendly editor available somewhere? =\

Unfortunately there is no custom UI for SSIS Pivot transform,yet (we do have one for unPivot, though), sorry.

SQL BOL should give enough information on how to config this transform, you can also check out Ash's blog http://sqljunkies.com/Article/705F07C3-69FE-4CAF-8CF8-CADBF145F372.scuk to see whether that helps. If any questions please let us know and we'd like to help.

thanks

wenyang

|||I know how to use it, it's just not very user friendly.|||When do you plan to release a friendly pivot editor?

Pivot transform not putting all values on same row

I have a pivot transform that it believe is configured correctly but is not distributing the values accross the columns on the same row. for example.

input:

id seqno codevalue

1 A red

1 B red

2 C blue

2 A green

2 B violet

3 A green

desired output:

id Seq_A Seq_B Seq_C

1 red red null

2 green violet blue

3 green null null

what I am getting:

id Seq_A Seq_B Seq_C

1 red null null

1 null red null

2 green null null

2 null violet null

2 null null blue

3 green null null

I do have the pivot usage for the id column set to 1. I have the pivot usage for seqno column set to 2 and codevalue column set to 3. I have the source column for each of the output columns set to the lineageID of the apprpriate input columns. I have the pivotKey values set for each of the destination columns. A for column Seq_A, B for column Seq_B, C for column Seq_C. All four columns have sortkey positions set; 1 for id, 2 for Seq_A, 3 for Seq_B and 4 for column SEQ_C.

It seems like the id column's pivot usage is not set to 1 like it should but when I check it is 1.

I also have several other pivot transforms in the same data flow and they are working as expected.

I have a suspicion that there is some hidden meta data that is messed up that is over-ridding my settings (just my guess) I have deleted this transform and re-done it several times, checking each configuration value, but still getting the same result.

Need some help or thoughts on making this work.

Thanks

Do you need to trim seqno before using it in a pivot? Might there be trailing white spaces or anything?|||

The input source has the column trimmed to char(1); I have done a dataviewer on the input and the output, and the input looks good. I have also recently (yesterday) installed SP2.

In my package, the pivot transform is after a union all transform. However, I have checked the output of the union all with a data viewer and the data input to the pivot transform looks good.

Earlier in my development of this dataflow, I did have some problems with the data source for this pivot transform, but I fixed it. And then checked the output of the pivot and found that it was not right. That is when I deleted the pivot transform and re-created it. But I still had the problem. I have since re-checked every configuration value in the pivot transform and the upstream and downstream transforms. All look to be configured correctly, but still the Pivot is putting each value on it's own row and not across the same row, for a given id.

pivot transform help

I need to transform the following layout by hopefully using the pivot transform, but am confused about the editor ......I have a compound primary key that I want to keep intact but then values in the row need to be broken out into their own row.

I need to go from this...

PKcol1 PKcol2 PKcol3 col4 col5 col6 col7

A 2007 1 Y N N N

A 2007 2 Y Y N N

A 2007 3 N N N Y

into this....

A 2007 1 col4 Y

A 2007 1 col5 N

A 2007 1 col6 N

A 2007 1 col7 N

A 2007 2 col4 Y

A 2007 2 col5 Y

A 2007 2 col6 N

A 2007 2 col7 N

A 2007 3 col4 N

A 2007 3 col5 N

A 2007 3 col6 N

A 2007 3 col7 Y

Can I do this using the pivot transform? Any suggestions?

The easiest way to accomplish this will be to transform the compound key into a single column key using the derived column transformation. You would then perform the pivot , then merge the dataflow back to include the compound key.

EDIT: It looks like you want the UNpivot transformation (that which takes you to a more normalized state). see http://technet.microsoft.com/en-us/library/ms141723.aspx

|||

Indeed the unpivot is exactly what I needed. Data flow is now as follows....

OLE DB selects the data

connect to Unpivot

Inside Unpivot editor, my PKcol1-PKcol3 above you check the pass-through box on the right. The other columns (col4-7) you check the other box. Then name the destination column, and put in values if you don't want the "Y" & "N".

Pivot Task Error - Duplicate pivot key

I am using the pivot task to to a pivot of YTD-Values and after that I use derived columns to calculate month values and do a unpivot then.

All worked fine, but now I get this error message:

[ytd_pivot [123]] Error: Duplicate pivot key value "6".

The settings in the advanced editor seem to be correct (no duplicate pivot key value) and I am extracting the data from the source sorted by month.

Could it be a problem that I use all pivot columns (month 1 to 12) in the derived colum transformation and they aren′t available at this moment while data extracting is still going on?

any hints?

Cheers
Markus

The pivot transform takes values like:

cust# Product Qty

-- -

1 Ham 4

1 Chips 2

1 Flan 1

2 Chips 3

2 Beer 19

and produces rows like:

cust# HamQty ChipsQty FlanQty BeerQty

-- - - - -

1 4 2 1 null

2 null 3 null 19

so what to do with input data like this?

cust# Product Qty

-- -

1 Ham 4

1 Chips 2

1 Chips 5

Which value should go into the ChipsQty column 2 or 5?

Most application would want 7, and so we suggest that the pivot be preceded by an aggregate transform to ensure that there is only 1 row for each distinct value of the pivot key. If not, you will see the error you report.

hope this helps

Pivot tables, Charts, Pivot chart

Hi all,

Can someone help me with some learning resources of Pivot Tables, Charts and Pivot Charts.

Thanx

Search for Pivot Table in Excel help you'll get some topics that explain these concepts and how to get started with them.

Here's one that came up that is online if you don't have Excel Help handy at the moment:

http://office.microsoft.com/training/training.aspx?AssetID=RC010136191033

Here are some more results to browse as well:

http://office.microsoft.com/en-us/results.aspx?Scope=DC%2CEM%2CES%2CFX%2CHA%2CHP%2CQZ%2CRC%2CTC%2CXT&Query=Pivot+Table

Hope that helps.

|||

Hello,

I am having issue with Performance of the Pivot Table connecting to OLAP Cubes. I am wondering if any of you have links to how to improve Pivot Table performance? Basically, I have done the backend optimization on the schema, but there should tricks on the Excel such as Connection Properties that I could use that could relate to MDX or Threshold Level that could speed up the Pivot Table performance. Below is some initial thoughts...

Non Empty Threshold=1

Any help is appreciated!

-Lawrence

Pivot tables, Charts, Pivot chart

Hi all,

Can someone help me with some learning resources of Pivot Tables, Charts and Pivot Charts.

Thanx

Search for Pivot Table in Excel help you'll get some topics that explain these concepts and how to get started with them.

Here's one that came up that is online if you don't have Excel Help handy at the moment:

http://office.microsoft.com/training/training.aspx?AssetID=RC010136191033

Here are some more results to browse as well:

http://office.microsoft.com/en-us/results.aspx?Scope=DC%2CEM%2CES%2CFX%2CHA%2CHP%2CQZ%2CRC%2CTC%2CXT&Query=Pivot+Table

Hope that helps.

|||

Hello,

I am having issue with Performance of the Pivot Table connecting to OLAP Cubes. I am wondering if any of you have links to how to improve Pivot Table performance? Basically, I have done the backend optimization on the schema, but there should tricks on the Excel such as Connection Properties that I could use that could relate to MDX or Threshold Level that could speed up the Pivot Table performance. Below is some initial thoughts...

Non Empty Threshold=1

Any help is appreciated!

-Lawrence

Pivot Tables using SQL

Hi,

I need some help in writing an SQL script that would convert the results into a pivot table in Toad. I am extracting data from an Oracle database.

I need to have each post date as a column header from the SQL below:

select ca.ACCOUNT_ID, cd.CLIENT_NAME, od.post_date, sum(oi.PRICE)
from order_details od, client_details cd, client_account ca, order_items oi
where od.DELETED = 0
and od.SERVICE_ID = 300009
and cd.CLIENT_ID = od.CLIENT_ID
and cd.CLIENT_ID = ca.CLIENT_ID
and od.ORDER_ID = oi.ORDER_ID
and od.INVOICE_DATE = oi.IDATE
group by ca.ACCOUNT_ID, cd.CLIENT_NAME, od.post_date

Thanks for any helpCheck here:

http://asktom.oracle.com/pls/ask/f?p=4950:8:16663421538065257584::NO::F4950_P8_DISP LAYID,F4950_P8_CRITERIA:7086279412131,
http://asktom.oracle.com/pls/ask/f?p=4950:8:16663421538065257584::NO::F4950_P8_DISP LAYID,F4950_P8_CRITERIA:419593546543,
http://asktom.oracle.com/pls/ask/f?p=4950:8:16663421538065257584::NO::F4950_P8_DISP LAYID,F4950_P8_CRITERIA:766825833740,
http://asktom.oracle.com/pls/ask/f?p=4950:8:16663421538065257584::NO::F4950_P8_DISP LAYID,F4950_P8_CRITERIA:925229353765,
:eek:|||Thanks...will have a look|||Also, this question has been asked and answered many times on many forums, just search for 'PIVOT TABLE' or 'CROSS TAB QUERY'. :D

Pivot Tables In Sql Server??

Hello Everybody,
Can anyone tell me how to create a pivot table in SQL Server?
I am attaching a picture of what the table should look like before and after the transformation. Thank you in advance.This is an FAQ.

This is handled in SQL 2005, but not in 2000 or 7.0. There are a couple of 3rd-party tools that create pivot-table-like structures. Look for RAC4SQL and SQL Crosstab.

Regards,

hmscott

Pivot Tables in Excel

I Created pivot tables and pivot charts in excel getting data from an external source (SQL Server 2000) using an ODBC Connection. The problem is when i want to use the same spreadsheet acceess the server from outside through the internet using an ODBC connection.

The odbc which access the sql server remotely uses as server name the ip address of the server than sql server running to.

The pivot tables when it was created it used the odbc connection accessed from with in the LAN (Server name /SERVERGROUP/SQLSERVER).

I was just wondering if there is an easy way to modify the code that the pivot tables uses to make the connection to the SQL Server with out
recreating all those pivot tables and pivot charts.

When I try to open the file remotely it fails to make a connection of course.

Any help is appreciated!

ThanksIf you are using an Excel Macro to do your queries, you are in luck. All you need to do is open the VB Editor and edit the connection string.

Otherwise, you will most likely have to recreate your queries (but if you do so, create a Macro, so you can edit it moreeasily in the future). All you need to do it turn on the Macro Recorder, build your queries as you did before, even perform any formatting, then stop the recorder. Now, if you ever need to tweek the query or change the datasource, it's simply a matter of editing the Marco code.

-b|||well thanks i knew that I could do that but I have over 20 graphs and 10 reports so it would be nice if there is a way for a quick and dirty solution. Saying all that if there is not a way to access the code that excel creates on the background when you use those pivot table wizards so I could manually modify the connection string then I guess I need to redo it from scrach and use macros this time.

Thanks for your input

Pivot Tables from Non-OLAP Databases?

Is it possible to create a Pivot Table while doing a webquery off of a Non-OLAP enabled MS SQL 2000 database? Here is the problem tho, I want the pivot tables to honor the Hierarchy (example, in the selection of the dimensions, if I pick USA I can expland USA and see all of the States, then pick PA and expland it and pick all of the Cities).

I have only been able to do this multi-level when a pivot table is created off of an OLAP piece.. PLEASE tell me there is a work around for this.I've embedded pivot tables in web pages that link directly to views in the database. The view must supply all the dimensions required, but then you get functionality similar to (but not exactly the same as) pivot tables in MS Excel.

blindman

Pivot Tables and MDX

Hi!
I want to write some MDX queries that pull the same data I'm retriving into
an excel pivot table that is hitting my cube. Up front, I'm pretty sure thi
s is not doable, but need to ask anyway. I want some way of hooking into th
e MSOLAP provider to see th
e MDX that's generated and sent to analysis services to retrieve the data in
to the pivot table. This would be an excellent shortcut to getting my MDX q
uery results to match what I'm getting in the pivot table.
Any anyone know of a way to see the MDX that's being generated from the pivo
t table?
-thanksInclude property Log File in your connection string.
Log File="C:\work\Sales_stock\mdx\excel_log\log.txt"
in log.txt you will find mdx queries.
Ramunas Balukonis
"brian p" <anonymous@.discussions.microsoft.com> wrote in message
news:399BECD7-270E-4539-BAC0-C628EB09D2B8@.microsoft.com...
> Hi!
> I want to write some MDX queries that pull the same data I'm retriving
into an excel pivot table that is hitting my cube. Up front, I'm pretty
sure this is not doable, but need to ask anyway. I want some way of hooking
into the MSOLAP provider to see the MDX that's generated and sent to
analysis services to retrieve the data into the pivot table. This would be
an excellent shortcut to getting my MDX query results to match what I'm
getting in the pivot table.
> Any anyone know of a way to see the MDX that's being generated from the
pivot table?
> -thanks

pivot tables & offline cube access

Is it possible to have multiple pivot tables in the same Excel workbook accessing the same offline cube file?

Currently, when the user is connected to the server it connects to a .asdatabase to populate many pivot tables. I need to allow the user to access a local cube file when they are not connected to the server.

I am using excel vba macros to connect the pivot caches to the online data source, which works perfectly. I would like to do the same to connect the pivot caches to the local cube file.

Is this possible? The local cube file is created off the server database using MDX (create global cube).

Thanks,
Lyn

If this is AS2005 - there is a bug in this area that is being fixed in the SP2 release. I think the fix would allow you to do what you've described.|||

Is this possible? The local cube file is created off the server database using MDX (create global cube).

yes possible , but there is a problem. u have to run this MDX statment manually , I tries to put it in a schedule in a jobs list , but it says the MDX syntax is worng, any help?

Karim

pivot tables & offline cube access

Is it possible to have multiple pivot tables in the same Excel workbook accessing the same offline cube file?

Currently, when the user is connected to the server it connects to a .asdatabase to populate many pivot tables. I need to allow the user to access a local cube file when they are not connected to the server.

I am using excel vba macros to connect the pivot caches to the online data source, which works perfectly. I would like to do the same to connect the pivot caches to the local cube file.

Is this possible? The local cube file is created off the server database using MDX (create global cube).

Thanks,
Lyn

If this is AS2005 - there is a bug in this area that is being fixed in the SP2 release. I think the fix would allow you to do what you've described.|||

Is this possible? The local cube file is created off the server database using MDX (create global cube).

yes possible , but there is a problem. u have to run this MDX statment manually , I tries to put it in a schedule in a jobs list , but it says the MDX syntax is worng, any help?

Karim

pivot tables & offline cube access

Is it possible to have multiple pivot tables in the same Excel workbook accessing the same offline cube file?

Currently, when the user is connected to the server it connects to a .asdatabase to populate many pivot tables. I need to allow the user to access a local cube file when they are not connected to the server.

I am using excel vba macros to connect the pivot caches to the online data source, which works perfectly. I would like to do the same to connect the pivot caches to the local cube file.

Is this possible? The local cube file is created off the server database using MDX (create global cube).

Thanks,
Lyn

If this is AS2005 - there is a bug in this area that is being fixed in the SP2 release. I think the fix would allow you to do what you've described.|||

Is this possible? The local cube file is created off the server database using MDX (create global cube).

yes possible , but there is a problem. u have to run this MDX statment manually , I tries to put it in a schedule in a jobs list , but it says the MDX syntax is worng, any help?

Karim

Pivot Tables

Hi,

I'm wanting to manipulate data between two tables in the following manner.

Table1

Column1 Derived Column ValueX ValueY

1 0 100 100

2 0 40 60

3 0 30 70

4 0 90 85

5 0 10 102

Table 2

IDColumn Qty1 Qty2 Qty3 Qty4 Qty5

a 10 20 30 40 50

I need to take the data in columns Qty1 - Qty5 in Table2 and transpose it into the Derived Column in Table 1.

Leaving the ValueX and ValueY columns as they are relative to column1.

I believe this can be done using a Pivot Table, but cannot find enough clear information from which to learn how to do it.

Any help will be welcomed.

John

hi,

your metadata misses the (eventual) relation between the 2 tables, as you obviously only reported a partial schema...

please consider posting a condesed schema with all required elements in a CREATE TABLE ( col1 datatype, colx datatype) format in order not to make us guessing all the metaschema..

considering 2 relations (tables) like

SET NOCOUNT ON;

USE tempdb;

GO

CREATE TABLE dbo.t1 (

Id int NOT NULL,

t2Ref char(1) NOT NULL,

derCol int NULL,

ValueX int NOT NULL,

ValueY int NOT NULL,

CONSTRAINT pk_t1 PRIMARY KEY (t2Ref, id)

);

CREATE TABLE dbo.t2 (

Id char(1) NOT NULL PRIMARY KEY,

Qty1 int NOT NULL,

Qty2 int NOT NULL,

Qty3 int NOT NULL,

Qty4 int NOT NULL,

Qty5 int NOT NULL

);

GO

INSERT INTO dbo.t1 VALUES ( 1 ,'a' , NULL, 100, 100 );

INSERT INTO dbo.t1 VALUES ( 2 ,'a', NULL, 40, 60 );

INSERT INTO dbo.t1 VALUES ( 3 ,'a', NULL, 30, 70 );

INSERT INTO dbo.t1 VALUES ( 4 ,'a', NULL, 90, 85 );

INSERT INTO dbo.t1 VALUES ( 5 ,'a', NULL, 10, 102 );

INSERT INTO dbo.t1 VALUES ( 1 ,'b' , NULL, 100, 100 );

INSERT INTO dbo.t1 VALUES ( 2 ,'b', NULL, 40, 60 );

INSERT INTO dbo.t1 VALUES ( 3 ,'b', NULL, 30, 70 );

INSERT INTO dbo.t1 VALUES ( 4 ,'b', NULL, 90, 85 );

INSERT INTO dbo.t1 VALUES ( 5 ,'b', NULL, 10, 102 );

INSERT INTO dbo.t2 VALUES ( 'a' , 10, 20, 30, 40, 50 );

INSERT INTO dbo.t2 VALUES ( 'b' , 100, 200, 300, 400, 500 );

which actually implies, for your unpivot to work that dbo.t1 always have 5 rows, from Id=1 to id=5 for each dbo.t1.t2Ref as the insert statements provides, you can rotate the the dbo.t2 table via the UNPIVOT statement, as you already pointed out, like

SELECT Id AS IdRef, CONVERT(int,RIGHT(IdRef,1)) AS Id, QT

FROM

(SELECT Id, Qty1, Qty2, Qty3, Qty4, Qty5

FROM dbo.t2) p

UNPIVOT

(QT FOR IdRef IN

(Qty1, Qty2, Qty3, Qty4, Qty5)

)AS unpvt

GO

--<--

IdRef Id QT

-- -- --

a 1 10

a 2 20

a 3 30

a 4 40

a 5 50

b 1 100

b 2 200

b 3 300

b 4 400

b 5 500

and you get an idea of the rotated output... you can then both project the joined result of the base dbo.t1 table with the work table resulting from the UNPIVOTing as

PRINT 'SELECT JOINED projection';

SELECT t1.Id, t1.t2Ref, r.IdRef, r.QT, t1.ValueX, t1.ValueY

FROM dbo.t1 t1

JOIN

(SELECT Id AS IdRef, CONVERT(int,RIGHT(IdRef,1)) AS Id, QT

FROM

(SELECT Id, Qty1, Qty2, Qty3, Qty4, Qty5

FROM dbo.t2) p

UNPIVOT

(QT FOR IdRef IN

(Qty1, Qty2, Qty3, Qty4, Qty5)

)AS unpvt ) AS r

ON r.IdRef= t1.t2Ref AND r.Id = t1.Id

ORDER BY t1.t2Ref, t1.Id;

--<

SELECT JOINED projection

Id t2Ref IdRef QT ValueX ValueY

-- -- -- -- -- --

1 a a 10 100 100

2 a a 20 40 60

3 a a 30 30 70

4 a a 40 90 85

5 a a 50 10 102

1 b b 100 100 100

2 b b 200 40 60

3 b b 300 30 70

4 b b 400 90 85

5 b b 500 10 102

and obviously code a JOINed UPDATE statement that updates the [derCol] from the projection of the upper SELECT as

PRINT 'UPDATEd JOIN';

UPDATE t1

SET derCol = r.QT

FROM dbo.t1 t1

JOIN

(SELECT Id AS IdRef, CONVERT(int,RIGHT(IdRef,1)) AS Id, QT

FROM

(SELECT Id, Qty1, Qty2, Qty3, Qty4, Qty5

FROM dbo.t2) p

UNPIVOT

(QT FOR IdRef IN

(Qty1, Qty2, Qty3, Qty4, Qty5)

)AS unpvt ) AS r

ON r.IdRef= t1.t2Ref AND r.Id = t1.Id;

the final output will be

SELECT * FROM dbo.t1;

--<-

Id t2Ref derCol ValueX ValueY

-- -- -- -- --

1 a 10 100 100

2 a 20 40 60

3 a 30 30 70

4 a 40 90 85

5 a 50 10 102

1 b 100 100 100

2 b 200 40 60

3 b 300 30 70

4 b 400 90 85

5 b 500 10 102

that should corespond to your requirements...

[COMPLETE SCRIPT]

SET NOCOUNT ON;

USE tempdb;

GO

CREATE TABLE dbo.t1 (

Id int NOT NULL,

t2Ref char(1) NOT NULL,

derCol int NULL,

ValueX int NOT NULL,

ValueY int NOT NULL,

CONSTRAINT pk_t1 PRIMARY KEY (t2Ref, id)

);

CREATE TABLE dbo.t2 (

Id char(1) NOT NULL PRIMARY KEY,

Qty1 int NOT NULL,

Qty2 int NOT NULL,

Qty3 int NOT NULL,

Qty4 int NOT NULL,

Qty5 int NOT NULL

);

GO

INSERT INTO dbo.t1 VALUES ( 1 ,'a' , NULL, 100, 100 );

INSERT INTO dbo.t1 VALUES ( 2 ,'a', NULL, 40, 60 );

INSERT INTO dbo.t1 VALUES ( 3 ,'a', NULL, 30, 70 );

INSERT INTO dbo.t1 VALUES ( 4 ,'a', NULL, 90, 85 );

INSERT INTO dbo.t1 VALUES ( 5 ,'a', NULL, 10, 102 );

INSERT INTO dbo.t1 VALUES ( 1 ,'b' , NULL, 100, 100 );

INSERT INTO dbo.t1 VALUES ( 2 ,'b', NULL, 40, 60 );

INSERT INTO dbo.t1 VALUES ( 3 ,'b', NULL, 30, 70 );

INSERT INTO dbo.t1 VALUES ( 4 ,'b', NULL, 90, 85 );

INSERT INTO dbo.t1 VALUES ( 5 ,'b', NULL, 10, 102 );

INSERT INTO dbo.t2 VALUES ( 'a' , 10, 20, 30, 40, 50 );

INSERT INTO dbo.t2 VALUES ( 'b' , 100, 200, 300, 400, 500 );

SELECT Id AS IdRef, CONVERT(int,RIGHT(IdRef,1)) AS Id, QT

FROM

(SELECT Id, Qty1, Qty2, Qty3, Qty4, Qty5

FROM dbo.t2) p

UNPIVOT

(QT FOR IdRef IN

(Qty1, Qty2, Qty3, Qty4, Qty5)

)AS unpvt

GO

GO

PRINT 'SELECT JOINED projection';

SELECT t1.Id, t1.t2Ref, r.IdRef, r.QT, t1.ValueX, t1.ValueY

FROM dbo.t1 t1

JOIN

(SELECT Id AS IdRef, CONVERT(int,RIGHT(IdRef,1)) AS Id, QT

FROM

(SELECT Id, Qty1, Qty2, Qty3, Qty4, Qty5

FROM dbo.t2) p

UNPIVOT

(QT FOR IdRef IN

(Qty1, Qty2, Qty3, Qty4, Qty5)

)AS unpvt ) AS r

ON r.IdRef= t1.t2Ref AND r.Id = t1.Id

ORDER BY t1.t2Ref, t1.Id;

PRINT 'UPDATEd JOIN';

UPDATE t1

SET derCol = r.QT

FROM dbo.t1 t1

JOIN

(SELECT Id AS IdRef, CONVERT(int,RIGHT(IdRef,1)) AS Id, QT

FROM

(SELECT Id, Qty1, Qty2, Qty3, Qty4, Qty5

FROM dbo.t2) p

UNPIVOT

(QT FOR IdRef IN

(Qty1, Qty2, Qty3, Qty4, Qty5)

)AS unpvt ) AS r

ON r.IdRef= t1.t2Ref AND r.Id = t1.Id;

SELECT * FROM dbo.t1;

GO

DROP TABLE dbo.t1, dbo.t2; -- clean up

[/COMPLETE SCRIPT] again, I assumed the existance of a dbo.t1.d2Ref column related to t2.Id column, without that all the scenario fades out.. regards|||

Thank you so much for your detailed answer, and my apologies for not providing enough information.

As a novice it's difficult to get an understanding of some of the basic things. eg. I was not sure that PIVOT always turns column data into a row, and UNPIVOT, does the opposite. I guessed that was the way it happened, but the examples on MSDN are certainly not clear enough for a beginner.

The example you have provided clarifies the situation for me, and should enable me to proceed.

Again, my sincere thanks for taking the time to answer.

John

Pivot Tables

Greetings, can anyone tell me how to create a pivot table view? (If at all) I want to manipluate data to a view to use in Crystal reports. Current table has producta "A", "B" & "C" with three options "i", "ii" & "iii" each with amounts per product & options:

A i 10
A ii 20
A iii 30
B i 5
B ii 7
B iii 9
C i 2
C ii 4
C iii 6

I want to create a view that lists the product "A" and Options "i" in the rows, with Colums "i", "ii" and "iii" and their corresponding amounts listed in the relevant colums. Thanx!there's probably a better solution out there, but this will get you started:

declare @.tbl table (
product char(1) not null, options char(3) not null, price money not null)
insert @.tbl values ('A', 'i', 10)
insert @.tbl values ('A', 'ii', 20)
insert @.tbl values ('A', 'iii', 30)
insert @.tbl values ('B', 'i', 5)
insert @.tbl values ('B', 'ii', 7)
insert @.tbl values ('B', 'iii', 9)
insert @.tbl values ('C', 'i', 2)
insert @.tbl values ('C', 'ii', 4)
insert @.tbl values ('C', 'iii', 6)

select p.product, [i]=t1.price, [ii]=t2.price, [iii]=t3.price
from (select distinct product from @.tbl) p
inner join @.tbl t1
on p.product = t1.product and t1.options = 'i'
inner join @.tbl t2
on p.product = t2.product and t2.options = 'ii'
inner join @.tbl t3
on p.product = t3.product and t3.options = 'iii'|||It sounds like you are trying to create a CROSSTAB query, and you can look up how to do it using CASE statements by searching Books Online for keyword "crosstab".

However, this will NOT give you a try pivot table report, which is dynamically configurable by the user. I'm not sure that Crystal can even do this. As a matter of fact, for a pivot table you don't want oto have your data in crosstab format. If you truly want pivot functionality and the ability to slice, dice, and summarize your data dynamically, create a pivot table in Excel or in an ASP page that links to the data in your table, (through a view, preferably), and leave your data in its current columnar format.

blindman|||actually crystal was able to do it even when it was part of vb4.0

but i still think that having this static approach is better than allowing users to build pivots dynamically, because if they transpose columns and rows (intentionally or not) the whole thing will croke (or may croke).|||Would this not be equivilent to a cube? It seems that A, B, and C would be one dimension, and i, ii, and iii would be a second dimension, and the values would be the intersection points of the the two dimensions...

| A | B | C
------
i | 10 | 5 | 2
------
ii | 20 | 7 | 4
------
iii | 30 | 9 | 6
------|||this is exactly what i was talking about in the previous post!|||Originally posted by ms_sql_dba
this is exactly what i was talking about in the previous post!

Bah.. sorry.. I started typing, and got side tracked for a little while and didn't get to finish my post until there had been 3 other replies!

SQL supports the creation of cubes if you didn't want to do a bunch of joins.. that might get costly if you had lots of dimensions...

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/olapdmad/agcubesintro_80qb.asp|||Thanx for the advice! Appreciate your time!

Pivot Tables

Can u direct me to a site to teaches about pivot tables(what they are and how to use them).Pivoting is changing the dymansion that you use to analyse the data.

This comes under datawarehousing and datamining. You should be able to find a detailed explanation under these topics.

Cheers,
Suren.

pivot table, calculated rows?

Hi,
Using SQL Server 2000 and I have a pivot table query that I'd now like to
total the rows making a calculated column. I've done this before on other
queries but can't seem to get it to work now. Any suggestions? Here's my
query as it stands now: (if you see something that could be improved in my
code feel free to suggest.)
SELECT p1.patient_id, p1.Patient,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 30) AND
(GETDATE()) THEN balance ELSE 0 END) AS R0,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 60) AND
(GETDATE() - 31) THEN balance ELSE 0 END) AS R30,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 90) AND
(GETDATE() - 61) THEN balance ELSE 0 END) AS R60,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 120) AND
(GETDATE() - 91) THEN balance ELSE 0 END) AS R90,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 150) AND
(GETDATE() - 121) THEN balance ELSE 0 END) AS R120,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 180) AND
(GETDATE() - 151) THEN balance ELSE 0 END) AS R150,
SUM(CASE WHEN transaction_date < (GETDATE() - 181)
THEN balance ELSE 0 END) AS R180
FROM
(SELECT DISTINCT claim.claim_number, pt.patient_id AS 'Patient_ID',
RTRIM(pt.last_name) + ', ' + ISNULL(RTRIM(pt.first_name), ' ') AS 'Patient',
amount.Balance,
( select max(posted_transaction_date)
from claim as c1
left join charge_on_claim as coc on coc.claim_sys_id = c1.sys_id
left join chg_item on chg_item.sys_id = coc.chg_item_sys_id
where c1.claim_number = claim.claim_number ) as 'Transaction_Date',
claim.status
FROM claim
LEFT JOIN ar_detail ON ar_detail.claim_sys_id = claim.sys_id
LEFT JOIN pt_policy ON pt_policy.sys_id = ar_detail.pt_policy_sys_id
LEFT JOIN patient AS pt ON pt.patient_id = pt_policy.patient_id
LEFT JOIN (SELECT claim.claim_number, SUM(amount) AS 'Balance'
FROM claim
LEFT JOIN ar_detail ON ar_detail.claim_sys_id = claim.sys_id
group by claim.claim_number) AS Amount ON Amount.claim_number =
claim.claim_number
WHERE amount.balance is not null) AS P1
GROUP BY patient_id, patient
ORDER BY p1.patient
I'd like to add another column which is the total of R0 - R180. If I simply
add this line to the selection:
, (R0 + R30 + R60 + R90 + R120 + R150 + R180) AS 'Total'
I get "Invalid column name 'R0'." error messages for each column. Hope that
makes sense.
Thanks,
LinnLinn Kubler,
You can use your query as a derived table.
select r0,...,r180, r0 +...+r180 as total
from ("here put your query") as t
or you can duplicate the code that calculates each r? column.
SELECT p1.patient_id, p1.Patient,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 30) AND
(GETDATE()) THEN balance ELSE 0 END) AS R0,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 60) AND
(GETDATE() - 31) THEN balance ELSE 0 END) AS R30,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 90) AND
(GETDATE() - 61) THEN balance ELSE 0 END) AS R60,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 120) AND
(GETDATE() - 91) THEN balance ELSE 0 END) AS R90,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 150) AND
(GETDATE() - 121) THEN balance ELSE 0 END) AS R120,
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 180) AND
(GETDATE() - 151) THEN balance ELSE 0 END) AS R150,
SUM(CASE WHEN transaction_date < (GETDATE() - 181)
THEN balance ELSE 0 END) AS R180,
(
SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 30) AND
(GETDATE()) THEN balance ELSE 0 END) +
... +
SUM(CASE WHEN transaction_date < (GETDATE() - 181)
THEN balance ELSE 0 END)
) as total
...
AMB
"Linn Kubler" wrote:

> Hi,
> Using SQL Server 2000 and I have a pivot table query that I'd now like to
> total the rows making a calculated column. I've done this before on other
> queries but can't seem to get it to work now. Any suggestions? Here's my
> query as it stands now: (if you see something that could be improved in m
y
> code feel free to suggest.)
> SELECT p1.patient_id, p1.Patient,
> SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 30) AND
> (GETDATE()) THEN balance ELSE 0 END) AS R0,
> SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 60) AND
> (GETDATE() - 31) THEN balance ELSE 0 END) AS R30,
> SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 90) AND
> (GETDATE() - 61) THEN balance ELSE 0 END) AS R60,
> SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 120) AND
> (GETDATE() - 91) THEN balance ELSE 0 END) AS R90,
> SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 150) AND
> (GETDATE() - 121) THEN balance ELSE 0 END) AS R120,
> SUM(CASE WHEN transaction_date BETWEEN (GETDATE() - 180) AND
> (GETDATE() - 151) THEN balance ELSE 0 END) AS R150,
> SUM(CASE WHEN transaction_date < (GETDATE() - 181)
> THEN balance ELSE 0 END) AS R180
> FROM
> (SELECT DISTINCT claim.claim_number, pt.patient_id AS 'Patient_ID',
> RTRIM(pt.last_name) + ', ' + ISNULL(RTRIM(pt.first_name), ' ') AS 'Patient
',
> amount.Balance,
> ( select max(posted_transaction_date)
> from claim as c1
> left join charge_on_claim as coc on coc.claim_sys_id = c1.sys_id
> left join chg_item on chg_item.sys_id = coc.chg_item_sys_id
> where c1.claim_number = claim.claim_number ) as 'Transaction_Date',
> claim.status
> FROM claim
> LEFT JOIN ar_detail ON ar_detail.claim_sys_id = claim.sys_id
> LEFT JOIN pt_policy ON pt_policy.sys_id = ar_detail.pt_policy_sys_id
> LEFT JOIN patient AS pt ON pt.patient_id = pt_policy.patient_id
> LEFT JOIN (SELECT claim.claim_number, SUM(amount) AS 'Balance'
> FROM claim
> LEFT JOIN ar_detail ON ar_detail.claim_sys_id = claim.sys_id
> group by claim.claim_number) AS Amount ON Amount.claim_number =
> claim.claim_number
> WHERE amount.balance is not null) AS P1
> GROUP BY patient_id, patient
> ORDER BY p1.patient
> I'd like to add another column which is the total of R0 - R180. If I simp
ly
> add this line to the selection:
> , (R0 + R30 + R60 + R90 + R120 + R150 + R180) AS 'Total'
> I get "Invalid column name 'R0'." error messages for each column. Hope th
at
> makes sense.
> Thanks,
> Linn
>
>

Pivot Table Woes

I am very confused here. I really hope someone can help.

I have a table that contains "virtual fields" (ie. a column for field name and a column for field value). What I'd like is a pivot table that has the field names across the top and the field values as the row. I found the PivotTable service, but that seems like quite a bit of work for something that you can do in Access in a few clicks. I also know the SUM/CASE method, but unfortunately the virtual fields are dynamic, and I don't know what they could be named, nor how many of them exist. Does anybody have any ideas of what I can do? I'll include an example below to clear up any confusion.

Thanks!

What I have:

field_name | field_value

----------------

car_manufacturer | Jaguar

car_model | XJR

car_horsepower | 390

car_manufactuer | Ford

car_model | Mustang GT

car_horsepower | 400

What I want:

car_manufacturer | car_model | car_horsepower

------------------------------

Jaguar | XJR | 390

Ford | Mustang GT | 400Complete a primary key

car_manufacturer | Jaguar
car_manufactuer | Ford
car_model | XJR
car_model | Mustang GT
car_horsepower | 400
car_horsepower | 390

1 | car_manufacturer | Jaguar
1 | car_model | XJR
1 | car_horsepower | 390
2 | car_manufactuer | Ford
2 | car_model | Mustang GT
2 | car_horsepower | 400

and add an ordering table of value names

1 | car_manufacturer
2 | car_model
3 | car_horsepower|||create table dbo.ValuesTable(GroupId int,ValueName varchar(50),Value varchar(100) not null,primary key (GroupID,ValueName))
GO
insert dbo.ValuesTable (GroupId,ValueName,Value) values (1,'car_manufacturer','Jaguar')
insert dbo.ValuesTable (GroupId,ValueName,Value) values (1,'car_model','XJR')
insert dbo.ValuesTable (GroupId,ValueName,Value) values (1,'car_horsepower','390')
insert dbo.ValuesTable (GroupId,ValueName,Value) values (2,'car_manufacturer','Ford')
insert dbo.ValuesTable (GroupId,ValueName,Value) values (2,'car_model','Mustang GT')
insert dbo.ValuesTable (GroupId,ValueName,Value) values (2,'car_horsepower','400')
GO

--without ordering
create function dbo.ufn_ConcatOrderingDistinct()
returns varchar(8000)
with schemabinding
as
begin
declare @.Res varchar(8000)
select @.Res = isnull(@.Res+',','')+'"'+ValueName+'"=max(case when d.ValueName = '''+ValueName+''''+' then d.Value end)'
from
(
select distinct ValueName
from dbo.ValuesTable
) x
return @.Res
end
GO
declare @.Exec varchar(8000)
set @.Exec='select '+dbo.ufn_ConcatOrderingDistinct()+'from dbo.ValuesTable d group by d.GroupId'
exec(@.Exec)
GO

--with ordering
create table dbo.OrderingTable(OrderId int primary key,ValueName varchar(50) not null)
GO
insert dbo.OrderingTable(OrderId,ValueName) values (1,'car_manufacturer')
insert dbo.OrderingTable(OrderId,ValueName) values (2,'car_model')
insert dbo.OrderingTable(OrderId,ValueName) values (3,'car_horsepower' )
GO
create function dbo.ufn_ConcatOrderingTable()
returns varchar(8000)
with schemabinding
as
begin
declare @.Res varchar(8000)
select @.Res = isnull(@.Res+',','')+'"'+ValueName+'"=max(case when d.ValueName = '''+ValueName+''''+' then d.Value end)'
from dbo.OrderingTable
order by OrderId
return @.Res
end
GO
declare @.Exec varchar(8000)
set @.Exec='select '+dbo.ufn_ConcatOrderingTable()+'from dbo.ValuesTable d group by d.GroupId'
exec(@.Exec)
GO|||create table #a (id int, fld varchar(40), val varchar(20))
insert #a select 1, 'car_manufacturer', 'Jaguar'
insert #a select 1, 'car_model', 'XJR'
insert #a select 1, 'car_horsepower', '390'
insert #a select 2, 'car_manufacturer', 'Ford'
insert #a select 2, 'car_model', 'Mustang GT'
insert #a select 2, 'car_horsepower', '400'
insert #a select 2, 'Doors', '4'

declare @.sql varchar(8000)

select @.sql = coalesce(@.sql+',','') + fld + ' = (select val from #a a1 where a1.fld = ''' + fld + ''' and a1.id = #a.id)'
from (select distinct fld from #a) as a
exec ('select id,' + @.sql+ ' from #a group by id')

drop table #a

gives
id car_horsepower car_manufacturer car_model Doors
---- ------- ------- ------- -------
1 390 Jaguar XJR NULL
2 400 Ford Mustang GT 4

You will have to split up the string if you have too many fields to fit in 8000 chars.

pivot table without aggregation?

Hello, I have a resultset as follows:

fields: Name, RankID

values:
Prorduct A, 4
Product B, 33
Product C, 221
(etc)

Name is always unique. RankID may not be.

I want to take that result set and basically pivot it to have the Name
values as columns, and the RankID of each one as the data. So you
would end up with only one row like:

Product A | Product B | Product C | etc
4 | 33 | 221 | etc

Is this possible? I do not want to sum the data or anything, simply
rotate it sort of.

Any advice is appreciated.Something like this should do it:

SELECT SUM(CASE WHEN [Name] = 'Product A' THEN RankID ELSE 0 END) AS
'Product A',
SUM(CASE WHEN [Name] = 'Product B' THEN RankID ELSE 0 END) AS
'Product B',
SUM(CASE WHEN [Name] = 'Product C' THEN RankID ELSE 0 END) AS
'Product C'
FROM PRODUCTS

Note that since your product name is unique the SUM here is just to pull the
data into one row. You could use MAX too but then if there is negative rank
you may have to handle it differently.

If this list of products is very dynamic, then you should look into dynamic
pivoting. Here are a few resources if you want to look in that direction:
http://www.sqlmag.com/articles/inde...articleid=15608
http://www.sqlmag.com/articles/inde...articleid=94268
http://www.sqlteam.com/item.asp?ItemID=2955
Also, most reporting tools have very good support for pivoting.

HTH,

Plamen Ratchev
http://www.SQLStudio.com|||Plamen Ratchev wrote:

Quote:

Originally Posted by

SELECT SUM(CASE WHEN [Name] = 'Product A' THEN RankID ELSE 0 END) AS
'Product A',
SUM(CASE WHEN [Name] = 'Product B' THEN RankID ELSE 0 END) AS
'Product B',
SUM(CASE WHEN [Name] = 'Product C' THEN RankID ELSE 0 END) AS
'Product C'
FROM PRODUCTS


I think SQL Server 2005 has a built-in pivoting function, but I've
never used it so I don't know the syntax.|||"Ed Murphy" <emurphy42@.socal.rr.comwrote in message
news:460c63e2$0$24701$4c368faf@.roadrunner.com...

Quote:

Originally Posted by

>
I think SQL Server 2005 has a built-in pivoting function, but I've
never used it so I don't know the syntax.


Here is how it can be done with PIVOT in SQL Server 2005:

SELECT [Product A],
[Product B],
[Product C]
FROM Products
PIVOT (SUM(RankID) FOR [Name] IN ([Product A],
[Product B],
[Product C])) AS P

I find the PIVOT syntax to be not so intuitive (unlike UNPIVOT which is
easier to use and understand).

Plamen Ratchev
http://www.SQLStudio.com

Pivot Table with SSAS 2005

hi

i facing problem when i tring to browse cube created in SSAS 2005 from pivot table in FP appear this error

The query could not be processed:

o An error was encountered in the transport layer.

o The peer prematurely closed the connection.

any one have solutions for this problem

thanks

Ensure that you have the Microsoft OLE DB Provider for Analysis Services 9.0 installed, as well as Microsoft Core XML Services 6.0. They can be downloaded here

http://www.microsoft.com/downloads/details.aspx?FamilyID=df0ba5aa-b4bd-4705-aa0a-b477ba72a9cb&DisplayLang=en

Once they are both installed, run regedit and look under HKEY_CLASSES_ROOT/MSOLAP - there should be a key called CLSID which should have the same value as the CLSID under HKEY_CLASSES_ROOT/MSOLAP.3

Now try to connect to the SSAS cube again...some people have found they need to specify their username as <Domain>\<Username> to connect correctly

Pivot table with no numeric aggregation?

I'm trying to pivot the data in a table but not aggregate numeric data, just rearrange the data in columns as opposed to rows.

For example, my initial table could be represented by this structure:

ID

Label

Value

1

a

val1

1

b

val2

1

c

val3

1

d

val4

1

e

val5

2

a

val6

2

b

val7

2

c

val8

2

d

val9

2

e

val10

and I am trying to get it into the following structure:

ID

Label a

Label b

Label c

Label d

Label e

1

val1

val2

val3

val4

val5

2

val6

val7

val8

val9

val10

The number of labels is known beforehand, so we know how many columns to make. I can get a first step at pivoting it with 'case' statements, but obviously still end up with a row for each Label/Value pair since there is no aggregate function being applied. So I'm not sure how to get it flattened down like shown above?

Thanks for any replies on this,

Eric

In SQL Server 2005, you can use the PIVOT operator like:

select pt.ID, pt.Angel as [Label a], pt.Beer as [Label b]...

from tbl as t

pivot (min(t.value) for t.Label in ( Angel, Beer, Coffee....)) as pt

In older versions, you can do below:

select t.ID

, min(case t.Label when 'a' then value end) as [Label a]

, min(case t.Label when 'b' then value end) as [Label b]

...

from tbl as t

group by t.ID

|||Thanks, works perfect! I had no idea you could use the min function on varchar.

Pivot table very slow

We are using MS SQL Server 2000 with its Analysis Services and Excel 2002.
We have 3 facts tables (less than 100 rows each) ,
8 dimensions (from 10 to 1000 members),
3 regular cubes and 1 virtual cube (with 20 calculated members).
The pivot table is produced from the virtual cube.
In Excel, when I put 2 dimensions side by side as row fields with all the calculated members,
it's very very slow (2-3 minutes).
When I remove 1 dimension as row field, it's fast (5 sec).
Or when I replaced all calculated members by regular measures (with 2 dimensions as row fields),
it's fast too !
I have tried different storage design or adding "default isolation mode=1" to Excel
connection string but it's still very slow.
Your help/suggestions will be very appreciated.
Thanks.
Create aggregation based on those two dimensions, or create an extra
dimension (dimension1 -> dimension 2), see if they help
Eric Li
SQL DBA
MCDBA
T.Huynh wrote:

> We are using MS SQL Server 2000 with its Analysis Services and Excel 2002.
> We have 3 facts tables (less than 100 rows each) ,
> 8 dimensions (from 10 to 1000 members),
> 3 regular cubes and 1 virtual cube (with 20 calculated members).
> The pivot table is produced from the virtual cube.
> In Excel, when I put 2 dimensions side by side as row fields with all the calculated members,
> it's very very slow (2-3 minutes).
> When I remove 1 dimension as row field, it's fast (5 sec).
> Or when I replaced all calculated members by regular measures (with 2 dimensions as row fields),
> it's fast too !
> I have tried different storage design or adding "default isolation mode=1" to Excel
> connection string but it's still very slow.
> Your help/suggestions will be very appreciated.
> Thanks.
>
|||How do you create an extra
dimension (dimension1 -> dimension 2) in Analysis Services ?
I have dim 1 (20 members) and dim 2 (1000 members).
Thanks for your advice.
|||Take a look to SQL Server Accelerator for BI. it includes an utility to
create your own Aggregations
ALEJANDRO LEGUIZAMO
MVP SQL - Colombia
"T Huynh" <anonymous@.discussions.microsoft.com> wrote in message
news:3D6120F1-228E-4E52-8BBA-E9F548970030@.microsoft.com...
> How do you create an extra
> dimension (dimension1 -> dimension 2) in Analysis Services ?
> I have dim 1 (20 members) and dim 2 (1000 members).
> Thanks for your advice.

Pivot table very slow

We are using MS SQL Server 2000 with its Analysis Services and Excel 2002.
We have 3 facts tables (less than 100 rows each) ,
8 dimensions (from 10 to 1000 members),
3 regular cubes and 1 virtual cube (with 20 calculated members).
The pivot table is produced from the virtual cube.
In Excel, when I put 2 dimensions side by side as row fields with all the ca
lculated members,
it's very very slow (2-3 minutes).
When I remove 1 dimension as row field, it's fast (5 sec).
Or when I replaced all calculated members by regular measures (with 2 dimens
ions as row fields),
it's fast too !
I have tried different storage design or adding "default isolation mode=1" t
o Excel
connection string but it's still very slow.
Your help/suggestions will be very appreciated.
Thanks.Create aggregation based on those two dimensions, or create an extra
dimension (dimension1 -> dimension 2), see if they help
Eric Li
SQL DBA
MCDBA
T.Huynh wrote:

> We are using MS SQL Server 2000 with its Analysis Services and Excel 2002.
> We have 3 facts tables (less than 100 rows each) ,
> 8 dimensions (from 10 to 1000 members),
> 3 regular cubes and 1 virtual cube (with 20 calculated members).
> The pivot table is produced from the virtual cube.
> In Excel, when I put 2 dimensions side by side as row fields with all the
calculated members,
> it's very very slow (2-3 minutes).
> When I remove 1 dimension as row field, it's fast (5 sec).
> Or when I replaced all calculated members by regular measures (with 2 dime
nsions as row fields),
> it's fast too !
> I have tried different storage design or adding "default isolation mode=1"
to Excel
> connection string but it's still very slow.
> Your help/suggestions will be very appreciated.
> Thanks.
>|||How do you create an extra
dimension (dimension1 -> dimension 2) in Analysis Services ?
I have dim 1 (20 members) and dim 2 (1000 members).
Thanks for your advice.|||Take a look to SQL Server Accelerator for BI. it includes an utility to
create your own Aggregations
ALEJANDRO LEGUIZAMO
MVP SQL - Colombia
"T Huynh" <anonymous@.discussions.microsoft.com> wrote in message
news:3D6120F1-228E-4E52-8BBA-E9F548970030@.microsoft.com...
> How do you create an extra
> dimension (dimension1 -> dimension 2) in Analysis Services ?
> I have dim 1 (20 members) and dim 2 (1000 members).
> Thanks for your advice.

PIVOT TABLE query !! @SNMSDN

hi ,

is it possible to do a pivot , where the number of columns is dynamic...i.e

i dont know how many rows will be selected , and i want to pivot them and insert into

a new (temp/tabletype)table...obv i dont know how many columns i need....

somethin like the example of books online pasted below , consider here that i need data for

all employees (distinct empid) , then pivot it, for that i'll need 'select distinct empid

from emp' in the pivot syntax 'FOR EmployeeID IN' .

pls tell me if such thing is possible or there is a turnaround for my problem...

SELECT VendorID, [164] AS Emp1, [198] AS Emp2, [223] AS Emp3, [231] AS Emp4, [233] AS Emp5
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( [164], [198], [223], [231], [233] )
) AS pvt
ORDER BY VendorID

you may try this (not sure for the perfs) :

declare @.sql1 as varchar(2000), @.sql2 as varchar(2000), @.sql3 as varchar(2000), @.empid as int

SET @.sql1 = 'SELECT VendorID '

SET @.sql2 = 'FROM (SELECT PurchaseOrderID, EmployeeID, VendorID FROM Purchasing.PurchaseOrderHeader) p '
SET @.sql2 = @.sql2 + 'PIVOT (COUNT (PurchaseOrderID) FOR EmployeeID IN ( '

SET @.sql3 = ') ) AS pvt ORDER BY VendorID'

DECLARE emp_cur CURSOR FAST_FORWARD FOR
SELECT DISTINCT EmployeeID FROM Purchasing.PurchaseOrderHeader

open emp_cur

fetch next from emp_cur into @.empid
while @.@.fetch_status = 0
begin
set @.sql1 = @.sql1 + ',' + cast(empid as varchar(10))
set @.sql2 = @.sql3 + cast(empid as varchar(10)) + ','
fetch next from emp_cur into @.empid
end

close emp_cur
deallocate emp_cur

set @.sql2 = LEFT(@.sql2, LEN(@.sql2)-1)

print @.sql1 + @.sql2 + @.sql3 -- For debug
exec (@.sql1 + @.sql2 + @.sql3)

|||

You have to create dynamic SQL and then execute it, the PIVOT statement does not support dynamic column lists itself.

You can get the list of columns by creating a variable and populating it like this

DECLARE @.pivotColumns nvarchar(2000), @.sql nvarchar(4000)
SET @.pivotColumns = ''
SELECT @.pivotColumns = @.pivotColumns + '[' + cast(EmployeeID AS nvarchar(10)) + '],'
FROM (SELECT distinct EmployeeID FROM Purchasing.PurchaseOrderHeader) p
SET @.pivotColumns = LEFT(@.pivotColumns, LEN(@.pivotColumns) - 1)
SET @.sql = 'SELECT *
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( ' + @.pivotColumns + ' )
) AS pvt
ORDER BY VendorID'
EXEC (@.sql)

There is a very nice article describing this here

http://www.theabstractionpoint.com/dynamiccolumns.asp

|||

Hello:

Could you check out this thread to see whether you can figure out something?

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=871809&SiteID=1

|||

thanks a lot buddy...actually i have a bit more tweek in my problem....i need the resultant recordset in a temp table.... as i dont know many columns will be in it , select into has to be used..now when i use it in buliding my query string and then execute it (@.sql) , later select * from temp , it ives an error... invalid object name '#temp' ...

(SELECT PurchaseOrderID, EmployeeID, VendorID
into #temp

FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( ' + @.pivotColumns + ' )
) AS pvt
ORDER BY VendorID'
EXEC (@.sql)

select * from #temp

-->some more help....

|||

The problem is that local temporary tables (with a # at the beginning of the name) are very local - so they are gone after the dynamic SQL finishes executing.

You could create a global temporary table (with two ## at the beginning of the name). The problem is that then the temp table will be available to all connections, so if it is possible that this code will ever run on two connections at the same time that won't work. So now you have to get tricky, you create the #temp table first (with the known VendorID column, but none of the other columns, because they are not known). Then you alter the table in the dynamic code before you insert.

DROP TABLE #temp
CREATE TABLE #temp(VendorID int)
DECLARE @.pivotColumns nvarchar(2000), @.alterColumns nvarchar(2000), @.sql nvarchar(4000)
SET @.pivotColumns = ''
SET @.alterColumns = ''
SELECT @.pivotColumns = @.pivotColumns + '[' + cast(EmployeeID AS nvarchar(10)) + '],',
@.alterColumns = @.alterColumns + '[' + cast(EmployeeID AS nvarchar(10)) + '] int,'
FROM (SELECT distinct EmployeeID FROM Purchasing.PurchaseOrderHeader) p
SET @.pivotColumns = LEFT(@.pivotColumns, LEN(@.pivotColumns) - 1)
SET @.alterColumns = LEFT(@.alterColumns, LEN(@.alterColumns) - 1)
SET @.sql = 'ALTER TABLE #temp
ADD ' + @.alterColumns
EXEC(@.sql)
SET @.sql = 'INSERT #temp
SELECT *
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( ' + @.pivotColumns + ' )
) AS pvt
ORDER BY VendorID'
EXEC (@.sql)

SELECT * FROM #temp

|||thanka a lot buddy....works perfect for me..

PIVOT TABLE query !!

hi ,

is it possible to do a pivot , where the number of columns is dynamic...i.e

i dont know how many rows will be selected , and i want to pivot them and insert into

a new (temp/tabletype)table...obv i dont know how many columns i need....

somethin like the example of books online pasted below , consider here that i need data for

all employees (distinct empid) , then pivot it, for that i'll need 'select distinct empid

from emp' in the pivot syntax 'FOR EmployeeID IN' .

pls tell me if such thing is possible or there is a turnaround for my problem...

SELECT VendorID, [164] AS Emp1, [198] AS Emp2, [223] AS Emp3, [231] AS Emp4, [233] AS Emp5
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( [164], [198], [223], [231], [233] )
) AS pvt
ORDER BY VendorID

you may try this (not sure for the perfs) :

declare @.sql1 as varchar(2000), @.sql2 as varchar(2000), @.sql3 as varchar(2000), @.empid as int

SET @.sql1 = 'SELECT VendorID '

SET @.sql2 = 'FROM (SELECT PurchaseOrderID, EmployeeID, VendorID FROM Purchasing.PurchaseOrderHeader) p '
SET @.sql2 = @.sql2 + 'PIVOT (COUNT (PurchaseOrderID) FOR EmployeeID IN ( '

SET @.sql3 = ') ) AS pvt ORDER BY VendorID'

DECLARE emp_cur CURSOR FAST_FORWARD FOR
SELECT DISTINCT EmployeeID FROM Purchasing.PurchaseOrderHeader

open emp_cur

fetch next from emp_cur into @.empid
while @.@.fetch_status = 0
begin
set @.sql1 = @.sql1 + ',' + cast(empid as varchar(10))
set @.sql2 = @.sql3 + cast(empid as varchar(10)) + ','
fetch next from emp_cur into @.empid
end

close emp_cur
deallocate emp_cur

set @.sql2 = LEFT(@.sql2, LEN(@.sql2)-1)

print @.sql1 + @.sql2 + @.sql3 -- For debug
exec (@.sql1 + @.sql2 + @.sql3)

|||

You have to create dynamic SQL and then execute it, the PIVOT statement does not support dynamic column lists itself.

You can get the list of columns by creating a variable and populating it like this

DECLARE @.pivotColumns nvarchar(2000), @.sql nvarchar(4000)
SET @.pivotColumns = ''
SELECT @.pivotColumns = @.pivotColumns + '[' + cast(EmployeeID AS nvarchar(10)) + '],'
FROM (SELECT distinct EmployeeID FROM Purchasing.PurchaseOrderHeader) p
SET @.pivotColumns = LEFT(@.pivotColumns, LEN(@.pivotColumns) - 1)
SET @.sql = 'SELECT *
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( ' + @.pivotColumns + ' )
) AS pvt
ORDER BY VendorID'
EXEC (@.sql)

There is a very nice article describing this here

http://www.theabstractionpoint.com/dynamiccolumns.asp

|||

Hello:

Could you check out this thread to see whether you can figure out something?

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=871809&SiteID=1

|||

thanks a lot buddy...actually i have a bit more tweek in my problem....i need the resultant recordset in a temp table.... as i dont know many columns will be in it , select into has to be used..now when i use it in buliding my query string and then execute it (@.sql) , later select * from temp , it ives an error... invalid object name '#temp' ...

(SELECT PurchaseOrderID, EmployeeID, VendorID
into #temp

FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( ' + @.pivotColumns + ' )
) AS pvt
ORDER BY VendorID'
EXEC (@.sql)

select * from #temp

-->some more help....

|||

The problem is that local temporary tables (with a # at the beginning of the name) are very local - so they are gone after the dynamic SQL finishes executing.

You could create a global temporary table (with two ## at the beginning of the name). The problem is that then the temp table will be available to all connections, so if it is possible that this code will ever run on two connections at the same time that won't work. So now you have to get tricky, you create the #temp table first (with the known VendorID column, but none of the other columns, because they are not known). Then you alter the table in the dynamic code before you insert.

DROP TABLE #temp
CREATE TABLE #temp(VendorID int)
DECLARE @.pivotColumns nvarchar(2000), @.alterColumns nvarchar(2000), @.sql nvarchar(4000)
SET @.pivotColumns = ''
SET @.alterColumns = ''
SELECT @.pivotColumns = @.pivotColumns + '[' + cast(EmployeeID AS nvarchar(10)) + '],',
@.alterColumns = @.alterColumns + '[' + cast(EmployeeID AS nvarchar(10)) + '] int,'
FROM (SELECT distinct EmployeeID FROM Purchasing.PurchaseOrderHeader) p
SET @.pivotColumns = LEFT(@.pivotColumns, LEN(@.pivotColumns) - 1)
SET @.alterColumns = LEFT(@.alterColumns, LEN(@.alterColumns) - 1)
SET @.sql = 'ALTER TABLE #temp
ADD ' + @.alterColumns
EXEC(@.sql)
SET @.sql = 'INSERT #temp
SELECT *
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( ' + @.pivotColumns + ' )
) AS pvt
ORDER BY VendorID'
EXEC (@.sql)

SELECT * FROM #temp

|||thanka a lot buddy....works perfect for me..

PIVOT TABLE query !!

hi ,

is it possible to do a pivot , where the number of columns is dynamic...i.e

i dont know how many rows will be selected , and i want to pivot them and insert into

a new (temp/tabletype)table...obv i dont know how many columns i need....

somethin like the example of books online pasted below , consider here that i need data for

all employees (distinct empid) , then pivot it, for that i'll need 'select distinct empid

from emp' in the pivot syntax 'FOR EmployeeID IN' .

pls tell me if such thing is possible or there is a turnaround for my problem...

SELECT VendorID, [164] AS Emp1, [198] AS Emp2, [223] AS Emp3, [231] AS Emp4, [233] AS Emp5
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( [164], [198], [223], [231], [233] )
) AS pvt
ORDER BY VendorID

you may try this (not sure for the perfs) :

declare @.sql1 as varchar(2000), @.sql2 as varchar(2000), @.sql3 as varchar(2000), @.empid as int

SET @.sql1 = 'SELECT VendorID '

SET @.sql2 = 'FROM (SELECT PurchaseOrderID, EmployeeID, VendorID FROM Purchasing.PurchaseOrderHeader) p '
SET @.sql2 = @.sql2 + 'PIVOT (COUNT (PurchaseOrderID) FOR EmployeeID IN ( '

SET @.sql3 = ') ) AS pvt ORDER BY VendorID'

DECLARE emp_cur CURSOR FAST_FORWARD FOR
SELECT DISTINCT EmployeeID FROM Purchasing.PurchaseOrderHeader

open emp_cur

fetch next from emp_cur into @.empid
while @.@.fetch_status = 0
begin
set @.sql1 = @.sql1 + ',' + cast(empid as varchar(10))
set @.sql2 = @.sql3 + cast(empid as varchar(10)) + ','
fetch next from emp_cur into @.empid
end

close emp_cur
deallocate emp_cur

set @.sql2 = LEFT(@.sql2, LEN(@.sql2)-1)

print @.sql1 + @.sql2 + @.sql3 -- For debug
exec (@.sql1 + @.sql2 + @.sql3)

|||

You have to create dynamic SQL and then execute it, the PIVOT statement does not support dynamic column lists itself.

You can get the list of columns by creating a variable and populating it like this

DECLARE @.pivotColumns nvarchar(2000), @.sql nvarchar(4000)
SET @.pivotColumns = ''
SELECT @.pivotColumns = @.pivotColumns + '[' + cast(EmployeeID AS nvarchar(10)) + '],'
FROM (SELECT distinct EmployeeID FROM Purchasing.PurchaseOrderHeader) p
SET @.pivotColumns = LEFT(@.pivotColumns, LEN(@.pivotColumns) - 1)
SET @.sql = 'SELECT *
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( ' + @.pivotColumns + ' )
) AS pvt
ORDER BY VendorID'
EXEC (@.sql)

There is a very nice article describing this here

http://www.theabstractionpoint.com/dynamiccolumns.asp

|||

Hello:

Could you check out this thread to see whether you can figure out something?

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=871809&SiteID=1

|||

thanks a lot buddy...actually i have a bit more tweek in my problem....i need the resultant recordset in a temp table.... as i dont know many columns will be in it , select into has to be used..now when i use it in buliding my query string and then execute it (@.sql) , later select * from temp , it ives an error... invalid object name '#temp' ...

(SELECT PurchaseOrderID, EmployeeID, VendorID
into #temp

FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( ' + @.pivotColumns + ' )
) AS pvt
ORDER BY VendorID'
EXEC (@.sql)

select * from #temp

-->some more help....

|||

The problem is that local temporary tables (with a # at the beginning of the name) are very local - so they are gone after the dynamic SQL finishes executing.

You could create a global temporary table (with two ## at the beginning of the name). The problem is that then the temp table will be available to all connections, so if it is possible that this code will ever run on two connections at the same time that won't work. So now you have to get tricky, you create the #temp table first (with the known VendorID column, but none of the other columns, because they are not known). Then you alter the table in the dynamic code before you insert.

DROP TABLE #temp
CREATE TABLE #temp(VendorID int)
DECLARE @.pivotColumns nvarchar(2000), @.alterColumns nvarchar(2000), @.sql nvarchar(4000)
SET @.pivotColumns = ''
SET @.alterColumns = ''
SELECT @.pivotColumns = @.pivotColumns + '[' + cast(EmployeeID AS nvarchar(10)) + '],',
@.alterColumns = @.alterColumns + '[' + cast(EmployeeID AS nvarchar(10)) + '] int,'
FROM (SELECT distinct EmployeeID FROM Purchasing.PurchaseOrderHeader) p
SET @.pivotColumns = LEFT(@.pivotColumns, LEN(@.pivotColumns) - 1)
SET @.alterColumns = LEFT(@.alterColumns, LEN(@.alterColumns) - 1)
SET @.sql = 'ALTER TABLE #temp
ADD ' + @.alterColumns
EXEC(@.sql)
SET @.sql = 'INSERT #temp
SELECT *
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( ' + @.pivotColumns + ' )
) AS pvt
ORDER BY VendorID'
EXEC (@.sql)

SELECT * FROM #temp

|||thanka a lot buddy....works perfect for me..

PIVOT TABLE QUERY

Hey guys, hopefully you can help me with my request... I am pretty new to SQL, so please bear with me..

I have a table on the system as follows

Item | Year | Month | ucivqa01 |AVG PRICE

ABC 2007 1 10 2.00

ABC 2007 2 10 2.10

ABC 2007 3 10 2.05

ABC 2007 4 10 2.30

ABC 2007 5 10 5.00

ABC 2007 6 10 1.95

XYZ 2007 1 10 100

XYZ 2007 2 10 112

XYZ 2007 3 10 111

XYZ 2007 4 10 100

XYZ 2007 5 10 105

XYZ 2007 6 10 104

I am trying to return the data in the following format:

ITEM MNTH1 MNTH2 MNTH3 MNTH4 MNTH5 MNTH 6 AVG1 AVG2 AVG3 AVG4 AVG5 AVG6

ABC 10 10 10 10 10 10 2.00 2.10 2.05 2.30 5.00 1.95

XYZ 10 10 10 10 10 10 100 112 111 100 105 104

This is only a small sample of the data, and i will be using the resulting SQL over a larger number or records. Also, the month and year will change. . I have a requirement to populate this data based on 41 months prior to the current month,

Anyway, i would appricate any help.

thanks

scotty

Here you go...

Code Snippet

Create Table #data (

Item Varchar(100) ,

Year Varchar(100) ,

Month int ,

ucivqa01 int ,

AVGPRICE float

);

Insert Into #data Values('ABC','2007','1','10','2.00');

Insert Into #data Values('ABC','2007','2','10','2.10');

Insert Into #data Values('ABC','2007','3','10','2.05');

Insert Into #data Values('ABC','2007','4','10','2.30');

Insert Into #data Values('ABC','2007','5','10','5.00');

Insert Into #data Values('ABC','2007','6','10','1.95');

Insert Into #data Values('XYZ','2007','1','10','100');

Insert Into #data Values('XYZ','2007','2','10','112');

Insert Into #data Values('XYZ','2007','3','10','111');

Insert Into #data Values('XYZ','2007','4','10','100');

Insert Into #data Values('XYZ','2007','5','10','105');

Insert Into #data Values('XYZ','2007','6','10','104');

Select

Item

,Max(Case When Year=2007 And Month=1 Then ucivqa01 End) Month1

,Max(Case When Year=2007 And Month=2 Then ucivqa01 End) Month2

,Max(Case When Year=2007 And Month=3 Then ucivqa01 End) Month3

,Max(Case When Year=2007 And Month=4 Then ucivqa01 End) Month4

,Max(Case When Year=2007 And Month=5 Then ucivqa01 End) Month5

,Max(Case When Year=2007 And Month=6 Then ucivqa01 End) Month6

,Avg(Case When Year=2007 And Month=1 Then AVGPRICE End) Avg1

,Avg(Case When Year=2007 And Month=2 Then AVGPRICE End) Avg2

,Avg(Case When Year=2007 And Month=3 Then AVGPRICE End) Avg3

,Avg(Case When Year=2007 And Month=4 Then AVGPRICE End) Avg4

,Avg(Case When Year=2007 And Month=5 Then AVGPRICE End) Avg5

,Avg(Case When Year=2007 And Month=6 Then AVGPRICE End) Avg6

From

#data

Group By

Item

|||

Thanks Manivannan, that is a great help.

I also heard from someone else about using the pivot command instead. From that i was able to build the following up:

(column names are different as this is live data)

SELECT*

FROM(SELECT ITEM, CUSTOMER, InvMONTH, QTY, [Unit Price], PrcMonth

FROM mvxreport.dmsexportstage1)

SOURCEQUERY PIVOT(max(QTY)FOR [InvMONTH] IN([INV1], [INV2], [INV3], [INV4], [INV5], [INV6]))

AS PIVOTTABLE PIVOT(

max([Unit Price])FOR [PrcMONTH] IN([PRC1], [PRC2], [PRC3], [PRC4], [PRC5], [PRC6]))AS PIVOTTABLE1

But when i do this, i cannot group by Item, Customer.. I get the results below:

9002-6050 AGCO NULL NULL NULL NULL 7 NULL NULL NULL NULL NULL 6.27 NULL 9002-6050 AIMS NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 9002-6050 AIMS NULL NULL 4 NULL NULL NULL NULL NULL 6.87 NULL NULL NULL 9002-6050 AIMS 6 NULL NULL NULL NULL NULL 6.87 NULL NULL NULL NULL NULL 9002-6050 AWBWA NULL NULL 4 NULL NULL NULL NULL NULL 5.97 NULL NULL NULL 9002-6050 BUNBURY NULL NULL NULL 6 NULL NULL NULL NULL NULL 5.882 NULL NULL 9002-6050 BUNBURY NULL NULL 3 NULL NULL NULL NULL NULL 5.883 NULL NULL NULL 9002-6050 CBCBROAD NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 9002-6050 CBCBROAD NULL NULL 7 NULL NULL NULL NULL NULL 5.731 NULL NULL NULL 9002-6050 CBCBROAD 16 NULL NULL NULL NULL NULL 5.732 NULL NULL NULL NULL NULL

I would like to have one line per item and Customer Combiniation..

Do you have any suggestions on this?

Thanks
Scotty

|||

Yes.. PIVOT is one of the nice operator. But your case it become hard. PIVOT operator is logically perfect if you want to pivot single column.

I tried to convert my previous query using PIVOT.

Create Table #data (

Item Varchar(100) ,

Year Varchar(100) ,

Month int ,

ucivqa01 int ,

AVGPRICE float

);

Insert Into #data Values('ABC','2007','1','10','2.00');

Insert Into #data Values('ABC','2007','2','10','2.10');

Insert Into #data Values('ABC','2007','3','10','2.05');

Insert Into #data Values('ABC','2007','4','10','2.30');

Insert Into #data Values('ABC','2007','5','10','5.00');

Insert Into #data Values('ABC','2007','6','10','1.95');

Insert Into #data Values('XYZ','2007','1','10','100');

Insert Into #data Values('XYZ','2007','2','10','112');

Insert Into #data Values('XYZ','2007','3','10','111');

Insert Into #data Values('XYZ','2007','4','10','100');

Insert Into #data Values('XYZ','2007','5','10','105');

Insert Into #data Values('XYZ','2007','6','10','104');

Code Snippet

Select * From

(

Select * From

(Select Item,Cast(Year as varchar) + '-' + Cast(Month as varchar) YearMonth,ucivqa01 From #data) as Data1

PIVOT

(

Max(ucivqa01) For YearMonth in ([2007-1], [2007-2], [2007-3], [2007-4], [2007-5], [2007-6])

) Pvt1

) as MaxData

Join

(

Select * From

(Select Item,Cast(Year as varchar) + '-' + Cast(Month as varchar) YearMonth,AVGPRICE From #data) as Data2

PIVOT

(

Avg(AVGPRICE) For YearMonth in ([2007-1], [2007-2], [2007-3], [2007-4], [2007-5], [2007-6])

) Pvt2

) as AVGData

on MaxData.Item=AVGData.Item