none
T-SQL: Select spalten wechseln RRS feed

  • Frage

  • Hallo,

    ich hab hier eine Tabelle die so aussieht:
    Id Text subId
    5 asdklr a
    5 rweae b
    5 sdfa c
    3 erae b
    3 fasdf c


    und diese will ich mithilfe eines selects so ausgeben:

    Id subId-a Text subId-b Text subId-c Text
    5 asdklr rweae sdfa
    3   erae fasdf


    weiß da eventuell jemand eine lösung?
    Dienstag, 5. Januar 2010 11:54

Antworten

  • Hallo Elly,
    meinst Du so etwas:
    declare @tab table(id int, [text] varchar(10), subid varchar(10));
    
    insert into @tab (id, [text], subid) values(5, 'asdklr', 'a');
    insert into @tab (id, [text], subid) values(5, 'rweae', 'b');
    insert into @tab (id, [text], subid) values(5, 'sdfa', 'c');
    insert into @tab (id, [text], subid) values(3, 'erae', 'b');
    insert into @tab (id, [text], subid) values(3, 'fasdf', 'c');
    
    SELECT id, [a] AS "subId-a Text",[b] AS "subId-b Text",[c] AS "subId-c Text"
    FROM @tab
    PIVOT (
    min([text]) 
    FOR subid 
    IN ( [a],[b],[c] )
    ) as x
    order by id desc;
    

    Das ist verwendbar ab SQL Server 2005. Ansonsten schau mal nach Kreuztabellenabfragen in den älteren Dokus.
    Einen schönen Tag noch, Christoph Muthmann Microsoft SQL Server MVP, http://www.insidesql.org
    Dienstag, 5. Januar 2010 13:05

Alle Antworten

  • Hallo Elly,
    meinst Du so etwas:
    declare @tab table(id int, [text] varchar(10), subid varchar(10));
    
    insert into @tab (id, [text], subid) values(5, 'asdklr', 'a');
    insert into @tab (id, [text], subid) values(5, 'rweae', 'b');
    insert into @tab (id, [text], subid) values(5, 'sdfa', 'c');
    insert into @tab (id, [text], subid) values(3, 'erae', 'b');
    insert into @tab (id, [text], subid) values(3, 'fasdf', 'c');
    
    SELECT id, [a] AS "subId-a Text",[b] AS "subId-b Text",[c] AS "subId-c Text"
    FROM @tab
    PIVOT (
    min([text]) 
    FOR subid 
    IN ( [a],[b],[c] )
    ) as x
    order by id desc;
    

    Das ist verwendbar ab SQL Server 2005. Ansonsten schau mal nach Kreuztabellenabfragen in den älteren Dokus.
    Einen schönen Tag noch, Christoph Muthmann Microsoft SQL Server MVP, http://www.insidesql.org
    Dienstag, 5. Januar 2010 13:05
  • Ok danke, meine Werte können sich blos beliebig un ständig verändern. Außer die SubIds gibt es nur von a-c
    Dienstag, 5. Januar 2010 13:41
  • Hallo Elly,

    dann passt die Lösung, den der einzige fixe Teil des Statement ist eben nur die SubIds mit [a], [b], [c].
    Olaf Helper ----------- * cogito ergo sum * errare humanum est * quote erat demonstrandum * Wenn ich denke, ist das ein Fehler und das beweise ich täglich http://olafhelper.over-blog.de
    Dienstag, 5. Januar 2010 15:41