在 T-SQL 中,給定輸入資料,例如
------ ------ -------- ------ ------ ------ -------- ------
| Col1 | Col2 | Col3 | Col4 | Col5 | Col6 | Col7 | Col8 |
------ ------ -------- ------ ------ ------ -------- ------
| 1 | 30 | 1.0000 | desc | NULL | NULL | NULL | NULL |
| 31 | 60 | 2.0000 | desc | NULL | NULL | NULL | NULL |
| 61 | 90 | 1.0000 | desc | NULL | NULL | NULL | NULL |
| NULL | NULL | NULL | NULL | 1 | 30 | 1.5000 | desc |
| NULL | NULL | NULL | NULL | 1 | 30 | 2.5000 | desc |
| NULL | NULL | NULL | NULL | 1 | 30 | 1.1000 | desc |
------ ------ -------- ------ ------ ------ -------- ------
我怎樣才能獲得這個輸出:
------ ------ -------- ------ ------ ------ -------- ------
| Col1 | Col2 | Col3 | Col4 | Col5 | Col6 | Col7 | Col8 |
------ ------ -------- ------ ------ ------ -------- ------
| 1 | 30 | 1.0000 | desc | 1 | 30 | 1.5000 | desc |
| 31 | 60 | 2.0000 | desc | 1 | 30 | 2.5000 | desc |
| 61 | 90 | 1.0000 | desc | 1 | 30 | 1.1000 | desc |
------ ------ -------- ------ ------ ------ -------- ------
輸入中的第 4、5 和 6 行“合并”以獲得所需的輸出。
如果總行數不均勻,這也應該有效。
uj5u.com熱心網友回復:
這是一個解決方案。如果給定表的右半部分的行數多于左半部分,則此方法不起作用。你可以看到我在做什么,你可以修改它來處理這種情況:
DECLARE @temp1 TABLE ( col1 INT, col2 INT, col3 DECIMAL(10,4), col4 NVARCHAR(20), col5 INT, col6 INT, col7 DECIMAL(10,4), col8 NVARCHAR(20) )
INSERT INTO @temp1 (col1,col2,col3,col4) VALUES
(1,30,1,'desc'),
(31,60,1,'desc'),
(61,90,1,'desc'),
(81,120,1,'desc')
INSERT INTO @temp1 (col5,col6,col7,col8) VALUES
(1,30,1.5,'desc'),
(1,30,2.5,'desc'),
(1,30,1.1,'desc')
SELECT col1,col2,col3,col4,col5,col6,col7,col8 FROM
(
SELECT col1,col2,col3,col4,ROW_NUMBER() OVER(ORDER BY col5) AS RowNumber FROM @temp1
WHERE col1 IS NOT NULL
) t1 LEFT JOIN
(
SELECT col5,col6,col7,col8,ROW_NUMBER() OVER(ORDER BY col1) AS RowNumber FROM @temp1
WHERE col5 IS NOT NULL
) t2 ON t1.RowNumber = t2.RowNumber
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446842.html
