+ Reply to Thread
Results 1 to 3 of 3

Rows to columns

  1. Rows to columns

    Hi guys,

    I need a little help with a query.

    I have 3 tables. One contain Items, the second thier properties and
    the third is used for cross reference between the items and thier
    properties.

    Here are the table definitions:

    Table invTypes
    typeID - int, primary
    typeName - nvarchar

    Table invAttibutes
    attributeID - int, primary
    attributeName - nvarchar
    attributeCategory - int

    Table invTypeAttibutes
    typeID - int
    attributeID - int
    valueInt - int


    When I run the following query:
    SELECT invTypes.typeName, dbo.invAttributeTypes.attributeName,
    invTypeAttributes.valueInt
    FROM invTypes INNER JOIN
    invTypeAttributes ON invTypes.typeID =
    invTypeAttributes.typeID INNER JOIN
    invAttributeTypes ON
    invTypeAttributes.attributeID = invAttributeTypes.attributeID
    WHERE (invAttributeTypes.attributeID = 5) OR
    (invAttributeTypes.attributeID = 6)

    I get the following result:

    itemName, attributeName, valueInt
    =========================
    Item 1, Attribute 5, 100
    Item 1, Attribute 6, 200
    Item 2, Attribute 5, 435
    Item 2, Attribute 6, 851
    Item 3, Attribute 5, 610
    Item 3, Attribute 6, 810
    Item 4, Attribute 5, 456
    Item 4, Attribute 6, 391

    What I want is to have is all of the attributes for a given item to be
    on one row, as in the following example:

    itemName, attributeName 5, attributeName 6
    =================================
    Item 1,100,200
    Item 2,435,851
    Item 3,610,810
    Item 4,456,391


    In general I want to transpose the rows for the different attributes
    to a separate columns, where each item has only one row.

    I don't know how to achive this.

    Any help will be greatly appreciated.



  2. Re: Rows to columns

    Here is one way:

    SELECT T.typeName,
    MAX(CASE WHEN A.attributeID = 5 THEN A.valueInt END) AS attr5,
    MAX(CASE WHEN A.attributeID = 6 THEN A.valueInt END) AS attr6
    FROM invTypes AS T
    INNER JOIN invTypeAttributes AS A
    ON T.typeID = A.typeID
    WHERE T.attributeID IN (5, 6)
    GROUP BY T.typeName;

    HTH,

    Plamen Ratchev
    http://www.SQLStudio.com

  3. Re: Rows to columns

    If your thinking crosstabs you should be thinking RAC.

    www.rac4sql.net

    www.beyondsql.blogspot.com



+ Reply to Thread