Unpivot SQL Query

  • 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.

  • 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![/I]

    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?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • 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![/I]

    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?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • 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.

  • 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![/I]

    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?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • 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![/I]

    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?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • 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?

  • Guess my question wasn't clear?

  • 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[/url]
    How to post performance related questions[/url]
    Links for Tally Table [/url] , Cross Tabs [/url] and Dynamic Cross Tabs [/url], Delimited Split Function[/url]

  • 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![/I]

    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?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

Viewing 10 posts - 1 through 9 (of 9 total)

You must be logged in to reply to this topic. Login to reply