我需要帮助在Sql Server 2014中进行查询。 我有下表
ID Part
SP470PR
SP470PR 181607
SP470PR 1030
我需要将结果显示如下:
ID Part
SP470PR 181607
SP470PR 1030
181607 SP470PR
181607 1030
1030 181607
1030 SP470PR
有人可以帮我解决这个问题吗? 我尝试使用Lead功能,但我无法得到我想要的结果?
谢谢
答案 0 :(得分:1)
尝试使用CROSS JOIN: -
Select * from table
where part is not null
union all
Select distinct a.part as ID,b.ID as part from
(select part from table) a
cross join
(select id from table) b
where part is not null
union all
Select a.part as ID,b.part from
(select part from table where part is not null) a
cross join
(select part from table where part is not null) b
where a.part<>b.part
答案 1 :(得分:0)
有一个非常小的数据样本,所以我不确定我是否正确,但在联盟的帮助下,我得到了这个:
创建并填充样本表(请在将来的问题中保存此步骤):
DECLARE @T AS TABLE
(
ID nvarchar(10),
Part nvarchar(10)
)
INSERT INTO @T VALUES
('SP470PR', NULL),
('SP470PR', '181607'),
('SP470PR', '1030')
查询:
SELECT ID, Part
FROM @T
WHERE Part IS NOT NULL
UNION
SELECT Part, ID
FROM @T
WHERE Part IS NOT NULL
UNION
SELECT t1.Part, t2.Part
FROM @T t1
INNER JOIN @T t2 ON t1.Id = t2.Id
WHERE t1.Part <> t2.Part
ORDER BY ID DESC, PART DESC
结果:
ID Part
SP470PR 181607
SP470PR 1030
181607 SP470PR
181607 1030
1030 SP470PR
1030 181607