我的数据格式如下
id idnew
1 2
3 4
2
4 7
6 8
7
结果应该是这样的
ID后应加上idnew
1
2
3
4
2
4
7
6
8
7
Thanks in advance
答案 0 :(得分:2)
这应该保持顺序:
SELECT id
FROM (
SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS RowNumber
FROM myTable
UNION ALL
SELECT idnew, ROW_NUMBER() OVER (ORDER BY idnew) +
(SELECT COUNT(*) FROM dbo.myTable) AS RowNumber
FROM myTable
WHERE idnew IS NOT NULL
) a
ORDER BY RowNumber
我假设id列不可为空。
注意:如果要保留idnew列中的NULL值并保持顺序,请在第二个选择中删除WHERE子句和ORDER BY id:
SELECT id
FROM (
SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS RowNumber
FROM myTable
UNION ALL
SELECT idnew, ROW_NUMBER() OVER (ORDER BY id) +
(SELECT COUNT(*) FROM dbo.myTable) AS RowNumber
FROM myTable
) a
ORDER BY RowNumber
答案 1 :(得分:1)
这已经过全面测试,请在这里尝试:https://rextester.com/DVZXO21058
按照您所描述的那样设置表格:
Makefile
以下是完成此操作的查询:
CREATE TABLE myTable (id INT, idnew INT);
INSERT INTO myTable (id, idnew)
VALUES (1, 2),
(3, 4),
(2, NULL),
(4, 7),
(6, 8),
(7, NULL);
SELECT * FROM myTable;
为了不进一步使查询复杂化,这是利用了'id'作为字符串优先于'idnew'的优势。我认为字符串排序不是这里的关键问题。
答案 2 :(得分:0)
使用交叉申请
;WITH CTE (id,idnew)
AS
(
SELECT 1,2 UNION ALL
SELECT 3,4 UNION ALL
SELECT 2,NULL UNION ALL
SELECT 4,7 UNION ALL
SELECT 6,8 UNION ALL
SELECT 7,NULL
)
SELECT New
FROM CTE
CROSS APPLY ( VALUES (id),(idnew))AS Dt (New)
WHERE dt.New IS NOT NULL
结果
New
---
1
2
3
4
2
4
7
6
8
7