Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Unpivot SQL Query Expand / Collapse
Author
Message
Posted Monday, October 7, 2013 3:23 PM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Friday, November 21, 2014 12:41 PM
Points: 100, Visits: 313
I have a table structure (tblmapping) like the following:

TableName ColumnName ColumnValue
Product ProductID 1
Product ProductID 2
Product ProductName Keyboard
Product ProductName Mouse

I want to convert from column based data to row based data. I tried the following query, but syntax errors:


SELECT col,value
FROM
(SELECT DISTINCT ColumnName
FROM tblMapping
WHERE TableName = 'Product') p
UNPIVOT
(ColumnValue FOR ColumnName IN (SELECT DISTINCT ColumnName
FROM tblMapping
WHERE TableName = 'Product')
) AS unpvt;

Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near ')'.

Not sure what I'm doing wrong. Thanks for the help.
Post #1502389
Posted Monday, October 7, 2013 6:25 PM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Today @ 6:03 PM
Points: 3,438, Visits: 5,394
I'm a bit confused by your question as I'm thinking maybe you need to PIVOT and not UNPIVOT.

Could you clarify by giving your expected results?



My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1502437
Posted Monday, October 7, 2013 6:47 PM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Today @ 6:03 PM
Points: 3,438, Visits: 5,394
Note this is cross-posted to the SQL 2005 forum. Please clarify which version of SQL you are working in.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1502440
Posted Monday, October 7, 2013 7:01 PM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Friday, November 21, 2014 12:41 PM
Points: 100, Visits: 313
I'm using SQL Server 2008 R2. However, I think the database might be configured to run as SQL Server 2005 (9.0).

The expected result that I want is:

ProductID ProductName
1 Keyboard
2 Mouse

Sorry for the confusion.
Post #1502442
Posted Monday, October 7, 2013 7:10 PM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Today @ 6:03 PM
Points: 3,438, Visits: 5,394
rs80 (10/7/2013)
I'm using SQL Server 2008 R2. However, I think the database might be configured to run as SQL Server 2005 (9.0).

The expected result that I want is:

ProductID ProductName
1 Keyboard
2 Mouse

Sorry for the confusion.


Unfortunately, that's what I thought. This is a PIVOT, not an UNPIVOT.
- The only way to convert data into column names is by using Dynamic SQL.
- The major issue here is that you're relying on row ordering (of the data saved in your table) to match up ProductID=1 with ProductName=Keyboard. That can't be guaranteed.

You could construct a dynamic SQL query that would appear to deliver the results you want, but I don't want to lead you down the garden path, thinking that solution will work for you in all cases.



My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1502443
Posted Monday, October 7, 2013 7:19 PM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Today @ 6:03 PM
Points: 3,438, Visits: 5,394
And by the way, I don't think you can "configure a 2008 server to run as 2005" but a 2008 server can run databases at a lower compatibility level.

Try this query:

SELECT name, compatibility_level FROM sys.databases;

Compatibility level=100 indicates the database runs at 2008 compatibility. I believe 90 is the compatibility level for SQL 2005.



My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1502444
Posted Monday, October 7, 2013 10:37 PM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Friday, November 21, 2014 12:41 PM
Points: 100, Visits: 313
Will try the compatibility.

Maybe you can help me with what I'm trying to achieve.

I have a table with the table name, column name, column values and whether the column values should be included or excluded.

This table is used to filter what data should be loaded. Here is an example

TableName ColumnName ColumnValue Include/Exclude
tblProduct ProductID 1 Exclude
tblProduct ProductID 2 Exclude
tblProduct ProductName Keyboard Include
tblProduct ProductName Mouse Include
tblOrder OrderID 1 Exclude
tblOrder OrderID 2 Exclude
tblOrder OrderName PackageA Exclude
tblOrder OrderName PackageB Exclude

So the queries should be:

DELETE FROM tblProduct WHERE ProductID NOT IN (1,2) AND ProductName IN ('Keyboad','Mouse')

DELETE FROM tblOrder WHERE Order NOT IN (1,2) AND OrderName NOT IN ('PackageA',''PackageB')

Do I have to use a cursor to loop thru each of the column name and filter on the column values?
Post #1502462
Posted Tuesday, October 8, 2013 5:26 PM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Friday, November 21, 2014 12:41 PM
Points: 100, Visits: 313
Guess my question wasn't clear?
Post #1502881
Posted Tuesday, October 8, 2013 5:50 PM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Today @ 4:20 PM
Points: 6,847, Visits: 13,393
You wouldn't need a c.u.r.s.o.r *cough*. It'll be dynamic SQL anyway (at least from my perspective...).
The question is:
How do you know, that the search conditions are combined using AND instead of OR?
There's no indication why
DELETE FROM tblProduct WHERE ProductID NOT IN (1,2) AND OR ProductName IN ('Keyboad','Mouse') wouldn't be correct either.... If "OR" comes into place, we'll need to talk about logical order and precedence. -> A AND (B OR C) or rather (A AND B) OR C or even (A OR C) AND B?

The current requirement also seems like to figure the data type on each and every value in order to determine the format the data need to be presented (e.g. numeric or character, or date??). It would make the task slightly less complicated, if the selected values could always be presented as character values (leading to implicit conversion in some cases and maybe to incorrect data in others, especially if DATE/DATETIME data type are involved)...




Lutz
A pessimist is an optimist with experience.

How to get fast answers to your question
How to post performance related questions
Links for Tally Table , Cross Tabs and Dynamic Cross Tabs , Delimited Split Function
Post #1502884
Posted Tuesday, October 8, 2013 6:07 PM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Today @ 6:03 PM
Points: 3,438, Visits: 5,394
rs80 (10/8/2013)
Guess my question wasn't clear?


I'm not clear on it. So far you've given us your control table. If you could give us that but instead as DDL and consumable sample data, it would be a start. Example:

DECLARE @Control TABLE
(
TableName VARCHAR(20)
,ColumnName VARCHAR(20)
,ColumnValue VARCHAR(100)
,IncludeExclude VARCHAR(10)
);

INSERT INTO @Control
SELECT 'tblProduct','ProductID','1','Exclude'
UNION ALL SELECT 'tblProduct','ProductID','2','Exclude'
UNION ALL SELECT 'tblProduct','ProductName','Keyboard','Include'
UNION ALL SELECT 'tblProduct','ProductName','Mouse','Include'
UNION ALL SELECT 'tblOrder','OrderID','1','Exclude'
UNION ALL SELECT 'tblOrder','OrderID','2','Exclude'
UNION ALL SELECT 'tblOrder','OrderName','PackageA','Exclude'
UNION ALL SELECT 'tblOrder','OrderName','PackageB','Exclude'

SELECT * FROM @Control


Now you also should provide the DDL for tbProducts and tbOrders, along with some consumable sample data.

Finally, we need to see what your expected results are.

You probably don't need a CURSOR. You may need Dynamic SQL although that's not for certain.



My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1502888
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse