Pivot-Like Query for Christmas?

SQL Server 2000. I have the following table and need to turn it into
something "flatter". Gurus, can you help me come up with any SQL
2000-compliant TSQL that can make this happen?

I have this:
CREATE TABLE #Pairs
(
       RowId Integer,
       ItemKey VARCHAR(50),
       ItemValue VARCHAR(50),
       ItemType VARCHAR(50),
	   ItemDesc  VARCHAR(50)
);
INSERT INTO #Pairs VALUES(1,'Height','84','Int','Height of the Door');
INSERT INTO #Pairs VALUES(2,'Width','40','Int','Widtrh of the door.');
INSERT INTO #Pairs VALUES(3,'Thickness','2','Int','Thickness of the
door.');
INSERT INTO #Pairs VALUES(4,'Color','White','VarChar(50)','Color of
the door.');

But I need to turn it into a table that looks like this:

RowId   Height   Width  Thickness  Color
1       84       null   null       null
2       null     40     null       null
3       null     null   2          null
4       null     null   null       White


Thanks and Merry Christmas!

0
SnapDive
12/26/2009 1:58:31 AM
sqlserver.programming 1873 articles. 0 followers. Follow

4 Replies
651 Views

Similar Articles

[PageSpeed] 37

EAV isn't the best database design, but here's a query that should generate 
the results you want.

SELECT RowId,
 CASE WHEN ItemKey = 'Height' THEN ItemValue END AS Height,
 CASE WHEN ItemKey = 'Width' THEN ItemValue END AS Width,
 CASE WHEN ItemKey = 'Thickness' THEN ItemValue END AS Thickness,
 CASE WHEN ItemKey = 'Color' THEN ItemValue END AS Color
FROM #Pairs;

-- 
Thanks

Michael Coles
SQL Server MVP
Author, "Expert SQL Server 2008 Encryption" 
(http://www.apress.com/book/view/1430224649)
----------------

"SnapDive" <SnapDive@community.nospam> wrote in message 
news:s9raj55gjer3kmfig9j45hpat00qcqce42@4ax.com...
>
> SQL Server 2000. I have the following table and need to turn it into
> something "flatter". Gurus, can you help me come up with any SQL
> 2000-compliant TSQL that can make this happen?
>
> I have this:
> CREATE TABLE #Pairs
> (
>       RowId Integer,
>       ItemKey VARCHAR(50),
>       ItemValue VARCHAR(50),
>       ItemType VARCHAR(50),
>    ItemDesc  VARCHAR(50)
> );
> INSERT INTO #Pairs VALUES(1,'Height','84','Int','Height of the Door');
> INSERT INTO #Pairs VALUES(2,'Width','40','Int','Widtrh of the door.');
> INSERT INTO #Pairs VALUES(3,'Thickness','2','Int','Thickness of the
> door.');
> INSERT INTO #Pairs VALUES(4,'Color','White','VarChar(50)','Color of
> the door.');
>
> But I need to turn it into a table that looks like this:
>
> RowId   Height   Width  Thickness  Color
> 1       84       null   null       null
> 2       null     40     null       null
> 3       null     null   2          null
> 4       null     null   null       White
>
>
> Thanks and Merry Christmas!
> 

0
Michael
12/26/2009 2:17:27 AM
Thanks for the fast response. My sample has just a few ItemKey but my
actual stuff has 60 and can grow to an unknown length. Do I have any
other option besides CASE WHEN?

Thanks.



On Fri, 25 Dec 2009 21:17:27 -0500, "Michael Coles"
<admin@geocodenet.com> wrote:

>EAV isn't the best database design, but here's a query that should generate 
>the results you want.
>
>SELECT RowId,
> CASE WHEN ItemKey = 'Height' THEN ItemValue END AS Height,
> CASE WHEN ItemKey = 'Width' THEN ItemValue END AS Width,
> CASE WHEN ItemKey = 'Thickness' THEN ItemValue END AS Thickness,
> CASE WHEN ItemKey = 'Color' THEN ItemValue END AS Color
>FROM #Pairs;

0
SnapDive
12/26/2009 2:35:54 AM
Google for EAV or "Entity Attribute Value" or insanely bad schema
designs to find find a few thousand words and examples of why we don't
do this in good SQL.
0
CELKO
12/26/2009 4:42:42 AM
SnapDive (SnapDive@community.nospam) writes:
> Thanks for the fast response. My sample has just a few ItemKey but my
> actual stuff has 60 and can grow to an unknown length. Do I have any
> other option besides CASE WHEN?
 
In that case you need to build the query dynamically. First read the 
actual ItemKey values, and then build the query from there. There is
nothing built in. A query in SQL returns a table, and a table has a 
well-defined set of columns.

You may also be interested in exploring RAC, a third-party product
which helps you this tedious work, http://www.rac4sql.net.

As for the EAV design, as pointed out by Michael Coles and Joe Celko, 
it is a design that comes with a whole bunch of problems, but there are
places where it is the best chioce. Whether yours is such a case, we don't
know.


-- 
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000: http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

0
Erland
12/26/2009 8:53:04 AM
Reply:

Similar Artilces:

Pivot Table Counting
I am having trouble trying to calculate fields through a pivot table. Basically, I have a data set that looks like this: Record Number State Value 1 CA 0 2 CA 12 3 CA 15 4 NJ 0 5 NJ 10 I want to set up a pivot table that will show 2 columns, one with th total number of records and one with the total number of records wit non-zero values. Both of the...

Pivot Tables #4
Hello you experts out there. I nned some Pivot table advice ( a website address for basics would be great), for instance how to excplain pivots and how to create them. I use lots of products with lots of sizes from various suppliers to name but a few columns. Is there a limit as to the amount of columns of data? Thank you very much. H Hi check out Debra Dalgleish's site - http://www.contextures.com/tiptech.html - she has a link to Jon Peltier's site which explains PT basics and then lots more interesting info on them. -- Cheers JulieD check out www.hcts.net.au/tipsandtric...

Paramter in UNION query
access 97, SQL 2005I am having issues with a UNION query. The query is prompting the userfor the apramter twice. I know if I create a form where the user cantype the parameter, I can reference the value from the form in thequery, but I am really not crazy about the idea of having to create anentire form just to get this query to run.Is there another way to have this prompt the user only once?Here is my query:SELECT dbo_tblJL_Main.MachineSNFROM dbo_tblJL_MainWHERE (((dbo_tblJL_Main.Customer) Like "*" & [Enter Customer Name:]&"*"));UNION SELECT tblTD_Main.MachineSNFRO...

Pivot Tables
Hi, I was windering if some one could provide me with a link to a tutorial for what I am trying to do. I have an aggregate table. This table has several groups and several columns. The intersection of a group and column is an aggreate value such as Sum function of a column value in that group. Normally a Pivot table shows 1 aggregate value at the intersection of a group and a column. What I want is: To show more than one value at the intersection besides the aggregate value. In other words, if a simple pivot table cell is: Aggr(x,y) where aggr is an aggregate function such a...

Report based on query w/subquery won't give a Report Footer total
I have a report that runs off a query which pulls item entry times per user. Each record in the table has an EntryStartTime field which is updated as soon as a user updates the first field in the entry form. (Technically the current time is stored in a global variable which is updated once the record is committed.) What I want to do is run a report showing how long it takes for a user to begin a new entry (i.e. the time between the start of record 1 and the start of record 2), and the average of those times. However, in my report, whenever I try to add a field in the Report Footer that...

Pivot Chart Formatting #5
How can I format a Pivot Chart and keep the customized format when refreshed? This is a known issue by Microsoft. Short answer, you can't do it. =( One possible work around is to record a macro of you setting the formatting of the chart, and then set it up so that the macro runs whenever the chart calculates. -- Best Regards, Luke M *Remember to click "yes" if this post helped you!* "Germeny Santos" wrote: > How can I format a Pivot Chart and keep the customized format when refreshed? Hi, This is dependent on what custom formatting you are refering to. T...

Create custom outline numbering in Word (like names of months).
To create an agenda of activities by month, I have to turn off the bulleting to type in the names of the months and then turn it on again to list the activities. I would like to be able to create a custom list that Word could pull from when I select my numbering style (so it would appear with "1, 2, 3" and "I, II, III" and the rest). I would then be able to create custom lists for the months of the year, or department names within our division, or employee names within a department, to make agendas that much easier to create. ---------------- This post...

CrossTab Query? 01-11-08
OK my brilliant pretties Riddle me this The fields: IncidentDate Region Agency CareItensity IncidentCategory IncidentSubCategory The dream: A report that lets me: Choose a time frame Gives me monthly total of incidents By Region/Agency/CareIntensity For IncidentCategory and IncidentSubCategory Like this - January Region = 1 Agency = Bob's Agency CareIntensity = Residential IncidentCategory = Death = Total IncidentSubCategory = Homicide = Total -- Thanks Post sample data & example of your expected results. -- KARL DEWEY Build a little - Test a little "knowshowrosegrows&...

Pivot table question: Sorting the subgroup in a pivot table (when using the top 10 option for the subgroup)
Hello: I have created a pivot table which has a one subgroup in the second column from the left. It uses the Top 10 option, so there are 10 subgroups So my data looks something like this: Group 1 50 Subgroup 1a 10 Subgroup 1b 40 Eight more subgroups Group 2 30 Subgroup 2a 20 Subgroup 2b 10 Eight more subgroups What I would like to do is sort by THe totals for Group 1, but then also sort by the subgroups, based on the values for each subgroup (similar to the "Sort by, ...

Update lookup query in subform
I have a form called 'player' on that form there is a sub form called 'classschedulesubfrm' inside the subform there is a lookup field that runs a query on the 'classes' table. on the main form 'player' I enter a persons class schedule if there is a class that is not in the database I click a button and the form 'classesfrm' opens and I add the class that is missing, close the form and then try to drop down the box in the 'lookupclass' control running the query to the classestbl and the newly entered data doesn't show up yet? I have t...

join multiple pivot tables?
How can I link up multiple pivottables all based on the same data where all i would have to do is change the page option (drop down menu) from the first pivot and the rest of the pivots would automatically adjust to match those? There's a sample file here in which you can change the page field in one pivot table, and all the related pivot tables change: http://www.contextures.com/excelfiles.html Under Pivot Tables, look for 'PT0021 - Change All Page Fields' or 'PT0008 - Change Multiple Page Fields' clueless_in_mempjhis wrote: > How can I link up mu...

Help with pivot table
I'm after some help with a pivot table I have created a work book to log certain defects, and would like to use a pivot table to show defects per unit on an improvement tracker, is it possible to have the pivot table to shift cells to the right when it is updated and required more columns so it doesn't overwrite data on the sheet it would be like this the componet fault unit numbers & Total defects are the pivot table & the action would be the start of the manual data Compontent Fault Unit Numbers Total Defects Action 1 2 3 4 5 Light Inop 1 1 ...

One final inventory query
I have inherited a large number of stock items which unfortunately were set to store values at 2dp. When the purchase order was created, the person set the order to be zero as the unit cost was £0.0019p and so rounded down to zero. The stock was then booked in at zero. Is there any way to open closed PO's once stock has been received, or must any changes be made from the utilities>inventory>adjust cost routine? Unfortunately whoever set the system up here did not envisage using more than 2dp. This affects a large number of stock items and we need to find the easiest way...

Can I permanently delete/hide data within Pivot Tables?
Microsoft Excel 2002 I have 155 clients which I need to run Pivot Tables for! All with the same pivot table layout. Is it possible to run the Pivot table with the 155 clients as a Template basically, then somehow delete or permanently hide the data leaving only one client, so that I can save multiple copies for each of the individual clients? Or can I set up a pivot table where I can automatically feed in parameters? Client details are stored on an Oracle database! Hi Peter, Right-click on a Page Field and select Field Settings from the context menu, then click the Advanced button. Yo...

Using formulas for pivot table
I know you have the count field but is there away to input a formula? For example customer ordered 25 cases and each case weighs 4 lbs and the end result would need to be total pounds ordered. Thanks! If you do the calculation in the pivot table you may not get the result that you expect. If possible, add a field to the source data, and calculate the order total there. Then, add the OrderTotal field to the pivot table's data area. tskb wrote: > I know you have the count field but is there away to input a formula? > For example customer ordered 25 cases and each case weighs 4 lbs...

Hyperlink in Pivot Table
Is it possible to put hyperlinks into a pivot table to go to the detail in other worksheets? I have a top 10 list of components with issues and would like the user to be able to click on the component to go to the list of issues. I thought if I put the hyperlink in the cell where the pivot table is getting it's info, it would come through, but that didn't work. Any suggestions? Thanks Hi Just double clicking on the cell with the data of interest, will open another sheet showing all of the entries making up that value. Delete the newly created sheet after you have finished w...

Pivot Tables #40
Does anyone know if there is a way to quickly clear a field list? I can't find a keyboard shortcut or anything else in any of the help/support avenues I've tried. Thanks in advance for the help. -- ERR229 Are you trying to clear all the check boxes in the field's dropdown list? In Excel 2002 and later versions, there's a Show All checkbox. In Excel 2000, and earlier versions, you can use programming to hide or show the items -- there's sample code here: http://www.contextures.com/xlPivot03.html ERR229 wrote: > Does anyone know if there is a way to quickl...

Business Portal "Copy to Excel" not working in Query pages
Hi, I am using Business Portal 4.0. When browsing through one of the queries pages in Business Portal, i clicked "Copy to Excel" icon. I got an error saying "The Office Web Components (OWC) must be installed to copy results to Excel." at the bottom. I am using Office 2007 on my machine. I came to know that Microsoft Office Web Components will no longer be shipping in Microsoft Office. I tried installing Office 2003 Add-in: Office Web Components from http://www.microsoft.com/downloads/details.aspx?familyid=7287252C-402E-4F72-97A5-E0FD290D4B76&displaylang=en a...

line column Pivot Charts
Access 2003 does not support combined Line/Column Charts, but Excel does. Has the capability been added to Access 2007? Access does support a series displayed as a bars and another series as line. -- Duane Hookom MS Access MVP Help me support UCP http://www.access.hookom.net/UCP/Default.htm "John" <John@discussions.microsoft.com> wrote in message news:A0DD25F6-D99A-44C3-812B-416776BED8AF@microsoft.com... > Access 2003 does not support combined Line/Column Charts, but Excel does. > Has > the capability been added to Access 2007? ...

deactivate the get pivot formula when I link a cell to a pivot
Currently I using excel 2003, but every time when I link the cell to a pivot table it will convert to a "Get pivot" formula. Is there any way I could deactivate it? See Debra Dalgleish's website for instructions: http://www.contextures.com/xlPivot06.html Does that help? *********** Regards, Ron XL2002, WinXP-Pro "hwtradezheng" wrote: > Currently I using excel 2003, but every time when I link the cell to a pivot > table it will convert to a "Get pivot" formula. Is there any way I could > deactivate it? ...

pivot table error (25000 rows!!)
I am trying to run a pivot table on a file containing 25000 rows. I have 5 duplicate (identical structure) files. The pivot works on each but one. On this file I get an error saying it has too many columns or rows in the pivot table. Drag at least one column or row off the table... Does anybody know what the reason for this message is, are their limits to rows or columns? The identical table works on the other files, therefore this message is so strange. Who has an idea? -- Craig_Richards ------------------------------------------------------------------------ Craig_Richards's Profil...

Pivot table move up command
Version: 2008 Operating System: Mac OS X 10.6 (Snow Leopard) I need to move up values in a pivot table to custom order them. When I right-click I see the &quot;Move&quot; menu, but the options to move up, move down, move to beginning and move to end are greyed out. Did you find an answer? Katy MelKC wrote: Pivot table move up command 04-Feb-10 Version: 2008 Operating System: Mac OS X 10.6 (Snow Leopard) I need to move up values in a pivot table to custom order them. When I right-click I see the &quot;Move&quot; menu, but the options to move up, move d...

Auto filter and Pivot Table
Is it possible to auto filter data, and use it as input to a Pivot table? When I run a test where I first auto filter, I initially had 20000 rows, and the auto filter reduced it to 12000 rows. But when I go to crearte a pivot table on the filtered data, I am back to a total record count of 20000. Am I combining apples and oranges? If so, is there a way to filter data, before it gets inputed to a Pivot table? -- RandyLewisKemp ------------------------------------------------------------------------ RandyLewisKemp's Profile: http://www.excelforum.com/member.php?action=getinfo&use...

Pivot Charts #4
Is there a way to change the pivot chart without changing the table in the process? ...

Import data from Parameter Query
I am trying to import data into Excel from a parameter query in Access. I keep getting a message "Too few parameters". I have tried supplying the parameter information via the filter in the import wizard but this did not work. I want to avoid removing the parameter in Access. Is there anyway around this? ...