2016-08-09 52 views
3

I wie unten eine SQL Server 2008-Tabelle haben ...Wählen Sie SQL-Spalten als zusätzliche Zeilen

ID Others1Desc Others1Value Others2Desc Others2value 
-- ----------- ------------ ----------- ------------ 
id_x xyz   12.50   pqr   10.00 
id_y abc   NULL   mno    1.05 

Jetzt will ich das Auswahlergebnis wie unten ...

ID ItemDesc  ItemValue 
-- ----------- ------------ 
id_x xyz   12.50 
id_x pqr   10.00 
id_y abc    NULL 
id_y mno    1.05 

Jede Führung ist hoch geschätzt. Dank

Antwort

3

Und ein anderer Weg ist mit cross apply und values clause wie diese

DECLARE @temp table (ID [varchar](100), Others1Desc [varchar](100), Others1Value decimal(11, 2), Others2Desc [varchar](100), Others2Value decimal(11, 2)); 

INSERT @temp (ID, Others1Desc, Others1Value, Others2Desc, Others2Value) VALUES ('id_x', 'xyz', 12.50, 'pqr', 10.00); 
INSERT @temp (ID, Others1Desc, Others1Value, Others2Desc, Others2Value) VALUES ('id_y', 'abc', NULL, 'mno', 1.05); 

select ID, t.* from @temp 
cross apply 
(
    values (Others1Desc, Others1Value), 
      (Others2Desc, Others2Value) 
) t(ItemDesc, ItemValue) 

Ergebnis

ID  ItemDesc ItemValue 
-------------------------- 
id_x xyz  12.50 
id_x pqr  10.00 
id_y abc  NULL 
id_y mno  1.05 
+1

Heute etwas gelernt. :) – Ash

1

Sie UNION ALL verwenden können, dies zu tun:

select ID, Others1Desc as ItemDesc, Others1Value as ItemValue 
from yourtable 
union all 
select ID, Others2Desc as ItemDesc, Others2Value as ItemValue 
from yourtable 
+0

Vielen Dank. manchmal werden einfachere Dinge ignoriert ... – Srinivas

1

Auf diese Weise:

select ID, Others1Desc as ItemDesc,Others1Value as itemValue from 
(select ID , Others1Desc , Others1Value from table1 

Union all 

select ID , Others2Desc, Others2value from table1)as a