在sql查询中选择2行2列

时间:2017-02-07 06:36:51

标签: sql sql-server

我有以下格式的数据:

ID          Vendor Name     Company Name

1                 VendorA         CompanyA

2                 VendorB         CompanyB

3                 VendorC         CompanyC

我想采用以下格式

ID                                     CompanyDetails     
1                                          CompanyA                                

1                                          VendorA                               

2                                          CompanyB

2                                          VendorB 

3                                          CompanyC

3                                           Vendor C

我使用过Union但是没有用, 请帮我写一个这个

的sql脚本

谢谢

5 个答案:

答案 0 :(得分:1)

json1.feeds.forEach(function(feed, i) {
  // This is your code, I've just copy-paster it here.
  console.log("\n The deails of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
});

答案 1 :(得分:0)

试试这个

SELECT ID, [Vendor Name] from table
union all
SELECT ID, [Company Name] from table
Order by ID

答案 2 :(得分:0)

试试这个会帮到你

select * into #tab from(
select 1 ID, 'VendorA' as [Vendor Name], 'CompanyA' [CompanyName]
union all
select 2, 'VendorB', 'CompanyB'
union all
select 3, 'VendorC', 'CompanyC'
)as a


select id,[Vendor Name] from #tab
union all
select id,[CompanyName] from #tab
order by  ID

答案 3 :(得分:0)

您可以设置订单以保留序列。

SELECT ID, CompanyDetails
FROM (
    SELECT ID, CompanyName AS CompanyDetails, 1 AS Ord
    FROM #table
    UNION
    SELECT ID, VendorName, 2 AS Ord
    FROM #table


) A
ORDER BY ID, Ord

答案 4 :(得分:0)

通过使用交叉应用和NTile,我们也可以实现

 Select ID,CompanyDetails 
        from (
Select NTILE(6)OVER(PARTITION BY COL ORDER BY COL DESC )ID ,
T.VAL As CompanyDetails 
            from (
select COL,VAL from  #Table1
CROSS APPLY(VALUES 
    ('Vendorname',[Vendor Name]),
    ('CompanyName',[CompanyName]))CS(COL,VAL))T)TT
    ORDER BY ID