Showing posts with label values. Show all posts
Showing posts with label values. Show all posts

Friday, March 30, 2012

Please help me out-no values for all the cells of the cubes?

Hi, all here,

I encountered a very very weird problem-I changed nothing, but suddenly all cell values are empty for one of my cubes? But the data is totally fine viewing from the data source view?

Why is that?

Please help me out and I am looking forward to hearing from you shortly.

With best regards,

Yours sincerely,

Hi, experts,

Please help me out!

I am looking forward to hearing from you.

Thanks.

With best regards,

Yours sincerely,

|||Hi

Make sure that you havne't remove the 'CALCULATE' command in your script editor under the calculations tab.

Chris.
|||

Hi,Chris,

Thank you so much indeed! I really appreciate your brilliant help so much!

With kindest regards,

Yours sincerely,

Monday, March 26, 2012

Please help

Tab1 and Tab2 has the following info.ID column in Tab1 and Tab2 has
matching values.
Tab3 should have the info as below.
Tab1
ID Val1 Val2
1 qqq sa
2 aaa fa
3 ddd we
Tab2
ID F1
1 A
1 B
1 C
1 D
2 F
2 G
3 H
Output Should be as blelow, without using the functions please advise the
sql query.
Tab3
ID Val1 Val2 F1
1 qqq sa A,B,C,D
2 aaa fa F,G
3 ddd we H
Thanks in advance.
It's not all that pretty, but the following function will do the job,
there may be more efficient approaches, but this one does work.
--============================================
CREATE FUNCTION JoinRows(@.id int)
RETURN varchar(50)
AS
BEGIN
DECLARE @.f1 char(1)
DECLARE @.str varchar(50)
SET @.f1 = ''
SET @.str = ''
WHILE 1=1
BEGIN
SELECT top 1 @.f1 = f1
,@.str = @.str + f1 + ','
FROM tab2
WHERE id = @.id
AND f1 > @.f1
IF @.@.rowcount = 0 BREAK
END
IF LEN(@.str) > 1
SET @.str = SUBSTRING(@.str,1,len(@.str)-1)
RETURN @.str
END
--============================================
-- This select query will then return Tab3
SELECT
*, dbo.JoinRows(id)
FROM tab1
Regards
Darren Gosbell [MCSD]
<dgosbell_at_yahoo_dot_com>
Blog: http://www.geekswithblogs.net/darrengosbell
In article <u4oLJnfxFHA.736@.tk2msftngp13.phx.gbl>, dkrreddy@.hotmail.com
says...
> Tab1 and Tab2 has the following info.ID column in Tab1 and Tab2 has
> matching values.
> Tab3 should have the info as below.
> Tab1
> --
> ID Val1 Val2
> 1 qqq sa
> 2 aaa fa
> 3 ddd we
>
> Tab2
> --
> ID F1
> 1 A
> 1 B
> 1 C
> 1 D
> 2 F
> 2 G
> 3 H
>
> Output Should be as blelow, without using the functions please advise the
> sql query.
> Tab3
> --
> ID Val1 Val2 F1
> 1 qqq sa A,B,C,D
> 2 aaa fa F,G
> 3 ddd we H
>
> Thanks in advance.
>
>
|||The following will work as well:
declare @.f1str varchar(100)
set @.f1str = ''
select @.f1str = @.f1str + f1 + ','
from F1
select @.f1str
You'd have to run it an ID at a time in a function but at least it's
only one execution per ID as opped to F1.
Hope that helps.

Friday, March 23, 2012

Please help

Tab1 and Tab2 has the following info.ID column in Tab1 and Tab2 has
matching values.
Tab3 should have the info as below.
Tab1
--
ID Val1 Val2
1 qqq sa
2 aaa fa
3 ddd we
Tab2
--
ID F1
1 A
1 B
1 C
1 D
2 F
2 G
3 H
Output Should be as blelow, without using the functions please advise the
sql query.
Tab3
--
ID Val1 Val2 F1
1 qqq sa A,B,C,D
2 aaa fa F,G
3 ddd we H
Thanks in advance.It's not all that pretty, but the following function will do the job,
there may be more efficient approaches, but this one does work.
-- ========================================
====
CREATE FUNCTION JoinRows(@.id int)
RETURN varchar(50)
AS
BEGIN
DECLARE @.f1 char(1)
DECLARE @.str varchar(50)
SET @.f1 = ''
SET @.str = ''
WHILE 1=1
BEGIN
SELECT top 1 @.f1 = f1
,@.str = @.str + f1 + ','
FROM tab2
WHERE id = @.id
AND f1 > @.f1
IF @.@.rowcount = 0 BREAK
END
IF LEN(@.str) > 1
SET @.str = SUBSTRING(@.str,1,len(@.str)-1)
RETURN @.str
END
-- ========================================
====
-- This select query will then return Tab3
SELECT
*, dbo.JoinRows(id)
FROM tab1
Regards
Darren Gosbell [MCSD]
<dgosbell_at_yahoo_dot_com>
Blog: http://www.geekswithblogs.net/darrengosbell
In article <u4oLJnfxFHA.736@.tk2msftngp13.phx.gbl>, dkrreddy@.hotmail.com
says...
> Tab1 and Tab2 has the following info.ID column in Tab1 and Tab2 has
> matching values.
> Tab3 should have the info as below.
> Tab1
> --
> ID Val1 Val2
> 1 qqq sa
> 2 aaa fa
> 3 ddd we
>
> Tab2
> --
> ID F1
> 1 A
> 1 B
> 1 C
> 1 D
> 2 F
> 2 G
> 3 H
>
> Output Should be as blelow, without using the functions please advise the
> sql query.
> Tab3
> --
> ID Val1 Val2 F1
> 1 qqq sa A,B,C,D
> 2 aaa fa F,G
> 3 ddd we H
>
> Thanks in advance.
>
>|||The following will work as well:
declare @.f1str varchar(100)
set @.f1str = ''
select @.f1str = @.f1str + f1 + ','
from F1
select @.f1str
You'd have to run it an ID at a time in a function but at least it's
only one execution per ID as opped to F1.
Hope that helps.sql

Wednesday, March 21, 2012

Please advise

Tab1 and Tab2 has the following info.ID column in Tab1 and Tab2 has
matching values.
Tab3 should have the info as below.
Tab1
--
ID Val1 Val2
1 qqq sa
2 aaa fa
3 ddd we
Tab2
--
ID F1
1 A
1 B
1 C
1 D
2 F
2 G
3 H
Output Should be as blelow, without using the functions please advise the
sql query.
Tab3
--
ID Val1 Val2 F1
1 qqq sa A,B,C,D
2 aaa fa F,G
3 ddd we H
Thanks in advance.See: http://www.aspfaq.com/show.asp?id=2529
Razvan|||See: http://www.aspfaq.com/show.asp?id=2529
Razvan

Friday, March 9, 2012

PL/SQL effeciency question

Right now I have a few PL/SQL procedures that calculate count(*) and sum(*) values for different reports. So far it's a daily operation, with around 80000 records per day (seems to be increasing by 10000 records every week though)

it's not a complex procedure, just a lot of number crunching for each columns. Right now the basic logic is to use a separate SQL statement for each column(with different conditions, of course), and repeat it until all the reports are filled in.

So far it's taking about 20 secs for going thru every 10000 records. Add the time it takes to load the records in (about 25-30 secs per 80000 records), and it becomes about 3 minutes of operation each day.

I have been thinking about how I can improve the performance of the procedure. So far I am thinking about whether the performance would improve if I can change the logic by declaring a cursor for the records, and just go thru it one time, then put the value into different variables.

Any suggestion is appreciated

MarkOriginally posted by mchih
Right now I have a few PL/SQL procedures that calculate count(*) and sum(*) values for different reports. So far it's a daily operation, with around 80000 records per day (seems to be increasing by 10000 records every week though)

it's not a complex procedure, just a lot of number crunching for each columns. Right now the basic logic is to use a separate SQL statement for each column(with different conditions, of course), and repeat it until all the reports are filled in.

So far it's taking about 20 secs for going thru every 10000 records. Add the time it takes to load the records in (about 25-30 secs per 80000 records), and it becomes about 3 minutes of operation each day.

I have been thinking about how I can improve the performance of the procedure. So far I am thinking about whether the performance would improve if I can change the logic by declaring a cursor for the records, and just go thru it one time, then put the value into different variables.

Any suggestion is appreciated

Mark
Generally it is preferable to avoid procedural logic if you want best performance. Maybe you could combine all (or many of) your counts and sums into a single query using DECODE (or CASE) to filter the records:

SELECT SUM( DECODE( col1, 'x', 1, 0 )) as COUNT_WHERE_COL1_IS X
, COUNT(*) TOTAL_COUNT,
, SUM( DECODE( col3, 123, col4, 0 )) as SUM_COL4_WHERE_COL3_IS_123
...
FROM ...|||it might be difficult to put many of the query together, since each of them has a different where clause.

eg:

table temp(
card_type
card_amount
message_type
message_response
.
.
.
)

a sample query would be
select count(*), sum(card_amount) from temp
where card_type = x
and message_type = y
and message_response = z;

now that i think about it, it might be possible to use a GROUP BY to get all the values with similar WHERE clause, but I don't know how to store the values individually so i can access them later (eg. put it into different table)

TIA

Mark

PL/SQL cursors and index tables

I'm trying to write a script that stores values in an index table using a cursor. My syntax looks write but i'm getting the following message:

Please enter the number of rows to be selected: 5
last_name_tbl last_name_tbl_type;
*
ERROR at line 9:
ORA-06550: line 43, column 27:
PL/SQL: ORA-00923: FROM keyword not found where expected
ORA-06550: line 43, column 4:
PL/SQL: SQL Statement ignoredOriginally posted by bbk
I'm trying to write a script that stores values in an index table using a cursor. My syntax looks write but i'm getting the following message:

Please enter the number of rows to be selected: 5
last_name_tbl last_name_tbl_type;
*
ERROR at line 9:
ORA-06550: line 43, column 27:
PL/SQL: ORA-00923: FROM keyword not found where expected
ORA-06550: line 43, column 4:
PL/SQL: SQL Statement ignored
Show your code

Wednesday, March 7, 2012

Pivoting Row Values into Colums

I'd like to get some data which includes month values bound to a data grid. The data is stored in a table like so:

Measure Month Value
A June 10.00
A July 9.00
A Aug 11.00
B Jun 100.00
B Jul 98.00
B Aug 99.00
C Jun 0.75
C Jul 0.8
C Aug 0.91

I need to report the data like this:
Measure Jun Jul August
A 10 9 11
B 100 98 99
C 75% 80% 91%

This was simple in classic ASP. Just use two recordsets, create a new table cell for each month using the first recordset then use the second recordset for each row.

But is there a way to "Pivot" or rotate the data so I can use the DataGrid? It only seems possible if each month has its own column field in table. Each month add a new column.

I can restructure the database, if needed.

I thought about creating a Cube, but that seems to have its own limitations. For example what if I want to add a Column for Quarter and year totals? I don't think it's possible to show multiple planes like that in an query of a cube.

It seems that this might be resolved in the presentation layer or the data layer. Any Suggestions?You can write a view or a stored procedure to produce the result set in your prefered format. The code below will only work when the same month has the same spelling in all rows. E.x., for June, always use either Jun or June. In the following example, I am assuming, Jun, Jul and Aug are used.


Select measure,
MAX(CASE [Month] WHEN 'Jun' THEN Value END) AS Jun,
MAX(CASE [Month] WHEN 'Jul' THEN Value END) AS Jul,
MAX(CASE [Month] WHEN 'Aug' THEN Value END) AS Aug
From YourTable
Group By Measure

Then you can bind the returned result set to your datagrid.

Pivoting large result sets

Heres the scenario:
We have a database that stores values for different characteristics taken at different times. The data is stored in the following format:

POSTED_UTS CHAR_ID RESULT_VALUE_FLOAT 2005-08-09 14:30:03.907 1859 1.08 2005-08-09 14:30:03.907 1860 1.07 2005-08-09 14:30:03.937 1861 0.01 2005-08-09 14:30:03.937 1859 0.01 2005-08-09 14:30:03.937 1860 0.01 2005-08-09 14:30:03.937 1861 0.01 2005-08-09 14:30:03.953 1756 0.01 2005-08-09 14:30:03.953 1757 0.01 2005-08-09 14:30:03.953 1859 0.01 2005-08-09 14:30:03.953 1859 0.01

The result set for a two hour time span returns >41,000 rows, the result set for a one week time span returns >2.9 million rows. We have multiple data sources, each with its own set of characteristics, each source takes readings at different times and then stores those readings in the above schema. The problem we are running into is, our end users want the data in the following format:

Posted UTS Char 1 Char 2 Char 3 Char 4 . . . Char <n> 2005-08-09 14:00:00.000 2.3 3.4 NULL NULL . . . <value n> 2005-08-09 14:00:30.000 2.3 3.4 5 66.8875 . . . <value n> 2005-08-09 14:00:00.000 NULL 3.4 NULL NULL . . . <value n> 2005-08-09 14:00:00.000 5.6 NULL NULL NULL . . . <value n>

Needless to say, when we pivot on a two hour block, it does take all that long (just over a minute), but when we try to pivot over a one week block, it takes considerably longer, much longer than anyone likes.

Is there a better way of doing this? Would storing the data in the same schema as we want to report in be wiser?

System Information: 2x XEON (Hyperthreaded to 4) 3Ghz
3GB ram
SQL Server 2005
Reporting Services 2005

Thanks for any help.

Wayne E. Pfeffer

The only fast solution I can think of is to use an ssas cube to pivot this

Philippe

pivoting a recordset

I have a reference table that looks like this

id | value
==========
1,abc
1,def
1,ghi
2,def
2,jkl

I want these values to go horizontally into another table matched on id, to look like this:

id | value
========
1,abc def ghi
2, def jkl

I built a cursor to parse through it but was taking forever (there's 185,000 records in the reference table). Any idea's on the fastest way to perform this function?never mind, I added an index to the destination table and it finished in 24 seconds :eek:

PIVOTing

Hi there!
I've played a little bit with the PIVOT operator in SQL Server 2005 and have
a question:
Can I use a Sub-Select for the values in the IN clause? Because I can't
hardcode these values because they are dynamic (based on user input)...
Thanks
Klaus Aschenbrenner
www.csharp.at,www.anecon.com
http://weblogs.asp.net/klaus.aschenbrennerKlaus
DECLARE @.st VARCHAR(50)
SET @.st='5,6'
EXEC('
SELECT *
FROM ItemAttributes AS ATR
PIVOT
(
MAX(value)
FOR attribute IN([artist], [name], [type], [height], [width])
) AS PVT
WHERE itemid IN('+@.st+')')
"Klaus Aschenbrenner" <Klaus.Aschenbrenner@.anecon.com> wrote in message
news:ea4lgqnRGHA.6084@.TK2MSFTNGP14.phx.gbl...
> Hi there!
> I've played a little bit with the PIVOT operator in SQL Server 2005 and
> have a question:
> Can I use a Sub-Select for the values in the IN clause? Because I can't
> hardcode these values because they are dynamic (based on user input)...
> Thanks
> Klaus Aschenbrenner
> www.csharp.at,www.anecon.com
> http://weblogs.asp.net/klaus.aschenbrenner
>|||> Can I use a Sub-Select for the values in the IN clause? Because I
> can't hardcode these values because they are dynamic (based on user
> input)...
Not in SQL Server 2005. Maybe next version...
Thank you,
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/

Saturday, February 25, 2012

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 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 table % and $ Formatting ?

Hi Guys

Just wondering after I've formatted certain facts say ie. Format String: Percentage and Format String: Currency all values are formatted correctly in AS however when I load the data in Excel pivot table all formatting is lost.

Is there anyway that I can allow formatting in pivot table ?

Thanks
TomSame problem here, and same interrogation.

Antoine.

pivot table % and $ Formatting ?

Hi Guys

Just wondering after I've formatted certain facts say ie. Format String: Percentage and Format String: Currency all values are formatted correctly in AS however when I load the data in Excel pivot table all formatting is lost.

Is there anyway that I can allow formatting in pivot table ?

Thanks
TomSame problem here, and same interrogation.

Antoine.

PIVOT statement whitout knowing values

Just a small issue...

I'm trying the new SQL 2005 (Express) because the PIVOT function was finally added.

I've a table with three columns ID, Height and Width

Now I'd like to have a table with for each height the number of ID for each Width

The easiest way is to use the PIVOT statement.....but..... to use it in SQL2005 I should use:

SELECT Height, [100] AS Width01, [200] AS Width02
FROM (

SELECT ID, Height, Width FROM TestTable) p

PIVOT ( COUNT (ID) FOR Width IN([100], [200]) ) AS pvt

This kind of querry works perfectly in a static situation, but if I add new record in the table referencing the "300" Width to obtain the correct result I have to modify the query.

Is there an options or a technique for having the list of the Width dinamically filled according the table contents.

Thank you very much to anyone how can help me

H

You have to use dynamic SQL to execute the SELECT statement after generating the values for the IN list. There is no other way using static SQL code.|||

To be clear, there are good reasons for this restriction.

SQL Server's PIVOT can exist anywhere in the query tree (unlike in Access), supports UNPIVOT (unlike Access), and does not require recompilation for each execution (unlike Access). These are good things for complex queries, as compilation time would be significantly worse if these did not exist.

SQL Server's query optimizer has a requirement that the column list be known before compilation begins. This allows faster compiles because we can identify duplicate alternatives more easily and avoid doing extra work during compilation. This also helps us to determine if we can avoid searching portions of the possible plan space that obviously will not help find a faster plan than what has been found so far during optimization.

I understand the desire to not have to bother specifying a column list, and perhaps that is something we can add in a future release. The reasons above are reasons it was not added in SQL 2005. Even if such a feature were added, it would be likely better if you could specify a column list to speed system throughput.

Conor Cunningham

SQL Server Query Optimization Development Lead

|||

Thank you all for the clear answer, now I understood that the restriction is due to performances.

Of course this type of restriction have very few impact over small databases like the ones I working on (~100 MB). So I will keep my application over access where the power of the TRANSFORM-PIVOT scheme will help me reducing the programming effort.

Thanks again

H

Monday, February 20, 2012

Pivot Multiple Values

Is there a way to pivot multiplie values in one 'run'.... In the order of ...

PIVOT ( SUM(DSH_TICKETS) FOR CPRF_NBR IN ([1], [2], [3], [4], [5])

SUM(HALL_CAPACITY) FOR CPRF_NBR IN ([1], [2], [3], [4], [5]) ) PVT

I know that there would be a problem with the headers, but that i could solve by using a second dummy for cprf_nbr and increase it with 10 (ex.)

Until knwo i did the jobg with a case statement, but it would be much nicer with a PIVOT.

No. This is not possible with PIVOT operator. You will have to use the old approach of using multiple aggregate functions with CASE expressions and GROUP BY which is what PIVOT does right now.|||

I am not 100% sure that this matches, but I wrote a blog about taking a set that looked like:

GroupBy PropertyName value1 value2
- -- --
First Property1 1.00 2.00
First Property2 2.00 4.00
Second Property1 4.00 8.00
Second Property2 8.00 16.00

And pivoted to look like:

groupBy Property1-value1 Property1-value2 Property2-value1 Property2-value2
- - -- - -
First 1.00 2.00 2.00 4.00
Second 4.00 8.00 8.00 16.00

The idea was to add another layer in there and Break down the set into two queries (in your case one for DSH_TICKETS, and another for HALL_CAPACITY) and then change the names of the columns to DSH_TICKETS-1, DSH_TICKETS-2, etc, then pivot on these names for the group.

Here it is: http://drsql.spaces.msn.com/blog/cns!80677FB08B3162E4!758.entry

There I used max, but sum should work (I think :)

Pivot Key Values

Is it possible to use a expression as a pivot key value?

I need to take data from one table and pivot it into another but what pivots to where is conditional, so I'm wondering if it's possible to say something like

"where Column1 = 'A' and Column2 = 'B' " in the pivot key value.

I'm trying to get it to work but can't, just keep getting the 'No pivot Key found' error.

Thanks

bobbins,

How many conditions are there? You could just use a conditional split to grab the records with the correct values per type and use a seperate chain for each, doing a union all to get them back together after the chain.

--

Looking at it more closely you are probably trying to unpivot (un-normalize). You could possibly use an expression to do the trick. The expression is located on the data flow task and is referenced in a manner similar to Unpivot.Unpivot Input.ColumnName.PivotKeyValue . (NOTE: both pivot and unpivot expose the pivotkeyvalue as data flow property expressions) Although, to be perfectly honest, I'm not sure if you will have access to the record information going through the pipe at the moment or not, so that might not work either...

|||You could pivot the values with a script. Using the script allows you a lot more flexibility in defining the pivoting rules.|||

Thanks for the replies, I am trying to de-normalize the data, here is a better explanation of what I'm trying to do:

My source data is an Ingres db on Unix:

MemberID Date Value Code Type 5029348 01/12/2006 79 A 1 5029348 01/12/2006 8 B 2 5029348 01/12/2006 4 C 3

I want to put the data in a de-normalized table so it looks like this:

MemberID Date ValueA1 ValueB2 ValueC3 5029348 01/12/2006 79 8 4

So my data mapping rules are:

Where Code = A and Type = 1 then map to ValueA1

Where Code = B and Type = 2 then map to ValueB2

Where Code = C and Type = 3 then map to ValueC3

I would like to do this as the data comes through the pipe instead of creating a staging table at either the source end or destination and then just bumping the data straight in from the staging table. I have limited experience with SSIS and want to learn but I'm struggling to work out what to do in the time I've been given to do this, hence my question about what you can actually put in the Pivot Key Values. A conditional split will split the values out but how do I put them all back together again as one row per MemberID to go into the destination? Or is there another way to do this?

Thanks again

|||

Take a look at this post. http://agilebi.com/cs/blogs/jwelch/archive/2007/05/18/dynamically-pivoting-columns-to-rows.aspx

You'll have to alter the script to not use the Split function, and apply your mapping rules, but it should provide a good starting point. If you are still having problems, post back here and we'll help.

Pivot Example when you don't know the exact values to Pivot on


Say, I have the following temporary table (@.tbl) where the QuestionID field will change values over time

Survey QuestionID Answer
1 1 1
1 2 0
2 1 1
2 2 2

I'd like to perform a pivot on it like this: select * from @.tbl Pivot (min(Answer) for QuestionID in ([1], [2])) as PivotTable

...however, I can't just name the [1], [2] values because they're going to change.

Instead of naming the values like this:
for QuestionID in ([1], [2], [3], [4])

I tried something like this:
for QuestionID in (select distinct QuestionID from @.tbl)

but am getting a syntax error. Is it possible to set up a pivot like this:
select * from @.tbl Pivot (min(Answer) for Question_CID in (select distinct @.QuestionID from @.tbl)) as PivotTable

or does anyone know another way to do it?

You cannot use a subquery in the IN for your pivot. I wish we could. Here is a dynamic solution:

Code Snippet

Create Table #tb1 (

Survey int,

QuestionID int,

Answer int

);

--Survey QuestionID Answer

--1 1 1

--1 2 0

--2 1 1

--2 2 2

--Sample Data

Insert Into #tb1 Values('1','1', '1');

Insert Into #tb1 Values('1','2', '0');

Insert Into #tb1 Values('2','1', '1');

Insert Into #tb1 Values('2','2', '2');

Insert Into #tb1 Values('3','3', '1');

--SELECT DISTINCT QuestionID FROM #tb1

SET

NOCOUNT ON

DECLARE

@.T AS TABLE(y nvarchar(20) NOT NULL PRIMARY KEY)

INSERT

INTO @.T SELECT DISTINCT QuestionID FROM #tb1

DECLARE

@.T1 AS TABLE(num int NOT NULL PRIMARY KEY)

DECLARE @.i AS int

SET @.i=1

WHILE @.i <20

BEGIN

INSERT INTO @.T1 SELECT @.i

SET @.i=@.i+1

END

DECLARE @.cols AS nvarchar(MAX), @.cols2 AS nvarchar(MAX),@.y AS nvarchar(20)

SET @.y = (SELECT MIN(y) FROM @.T)

SET @.cols = N''

SET @.cols2 = N''

WHILE @.y IS NOT NULL

BEGIN

SET @.cols = @.cols + N',['+CAST(@.y AS nvarchar(20))+N']'

SET @.cols2 = @.cols2 + N'+ coalesce(['+CAST(@.y AS nvarchar(20))+N'],'''')'

SET @.y = (SELECT MIN(y) FROM @.T WHERE y > @.y)

END

SET @.cols = SUBSTRING(@.cols, 2, LEN(@.cols))

SET @.cols2 = SUBSTRING(@.cols2, 2, LEN(@.cols2)-1)

DECLARE @.sql AS nvarchar(MAX)

SET @.sql = N'SELECT Survey, ' +@.cols + N' FROM (SELECT Survey, QuestionID, Answer FROM #tb1) as t

PIVOT (Min(Answer) FOR QuestionID IN(' + @.cols + N')) AS pvt'

EXEC sp_executesql @.sql

print @.sql

drop table #tb1

|||

Try:

Code Snippet

use tempdb

go

create table #t1 (

survey int,

questionid int,

answer int

)

insert into #t1 values(1,1, 1)

insert into #t1 values(1,2, 0)

insert into #t1 values(2,1, 1)

insert into #t1 values(2,2, 2)

insert into #t1 values(0,0, 1)

declare @.cols nvarchar(max)

declare @.sql nvarchar(max)

set @.cols = stuff(

(

select ',' + quotename(QuestionID)

from (select distinct QuestionID from #t1) as t

order by QuestionID

for xml path('')

), 1, 1, '')

set @.sql = N'

select

Survey, ' + @.cols + N'

from

#t1

pivot

(

min(Answer)

for QuestionID in (' + @.cols + N')

) as pvt

'

exec sp_executesql @.sql

drop table #t1

go

In case you do not want to see the NULL values, take a look to this post. There I posted a similar solution.

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

Be careful with SQL Injection.

PIVOT on Steroids

http://www.sqlmag.com/Article/ArticleID/94268/sql_server_94268.html

AMB