[英]Select one column data in different columns in SQL Server
我必须匹配两个表table1和table2,对于table1的一行,我在表2中有两行或更多行,我想在一行中显示它们。
现在我有以下内容:
Select
a.[ID], b.[Description]
From
table1 a, table2 b
Where
a.[ID] = b.[ID];
输出:
[ID] | [Description]
-----+--------------
1 | Fee
1 | Domestic Fee
2 | Fee
2 | International Fee
我想得到以下结果
[ID] | [Description1] | [Description2]
-----+----------------+---------------
1 | Fee | Domestic Fee
2 | Fee | International Fee
先感谢您 :)
如果您有多个描述,则可以如下使用Pivot:
Select * from (
Select *, RowN = Concat('Description', Row_Number() over (partition by Id order by Id)) from #description ) a
pivot (max([Description]) for RowN in ([Description1],[Description2])) p
输出如下:
+----+--------------+-------------------+
| Id | Description1 | Description2 |
+----+--------------+-------------------+
| 1 | Fee | Domestic Fee |
| 2 | Fee | International Fee |
+----+--------------+-------------------+
这是我对交叉申请运营商的建议
数据准备:
create table tst_1 (id int, dsc nvarchar(30))
insert into tst_1 (id, dsc)
values (1,'Fee'),(1,'Domestic Fee'),(2,'Fee'),(2,'International Fee')
带有jon的下一个简单选择显示您想要的数据:
select t1.id, t1.dsc, x.dsc
from tst_1 t1
cross apply ( select row_number() over (order by id) as lp
,id
,dsc
from tst_1 )x
where x.id = t1.id and x.dsc <> t1.dsc
and lp%2 = 0
tst_1
可以是基于您select ...
问题的视图。
Select
a.[ID],a.[Description], b.[Description]
From
table1 a left outer join table2 b
on
a.[ID] = b.[ID];``
尝试这个:
select ID, DESCRIPTION1, DESCRIPTION2
from
(
Select a.[ID]
,b.[Description]
,'DESCRIPTION' + CAST(ROW_NUMBER() OVER(PARTITION BY a.ID ORDER BY a.ID) AS VARCHAR(255))AS RN
from table1 a
JOIN table2 b ON a.[ID] = b.[ID]
) d
pivot
(
max([Description])
for RN in (DESCRIPTION1,DESCRIPTION2)
) piv;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.