我的sql server中有一个表。该表有一列。
示例表名:Sample
列名:数据
数据
-----------
7/11/2014 12:00:00 AM
7/31/2014 12:00:00 AM
8/21/2014 12:00:00 AM
9/19/2014 12:00:00 AM
11/20/2014 12:00:00 AM
12/18/2014 12:00:00 AM
1/22/2015 12:00:00 AM
所以通过这个数据,我想添加一个额外的列,在那个列中,我希望第二行数据进入第一行,第三行数据进入第二行......等等。
示例:
data New Column
----------- ----------------------
7/11/2014 12:00:00 AM 7/31/2014 12:00:00 AM
7/31/2014 12:00:00 AM 8/21/2014 12:00:00 AM
8/21/2014 12:00:00 AM 9/19/2014 12:00:00 AM
9/19/2014 12:00:00 AM 11/20/2014 12:00:00 AM
11/20/2014 12:00:00 AM 12/18/2014 12:00:00 AM
12/18/2014 12:00:00 AM 1/22/2015 12:00:00 AM
1/22/2015 12:00:00 AM Null
向我提供如何获得预期输出的建议。
答案 0 :(得分:0)
测试数据
DECLARE @Table TABLE (DateColumn DATETIME)
INSERT INTO @Table VALUES
('7/11/2014 12:00:00 AM'),
('7/31/2014 12:00:00 AM'),
('8/21/2014 12:00:00 AM'),
('9/19/2014 12:00:00 AM'),
('11/20/2014 12:00:00 AM'),
('12/18/2014 12:00:00 AM'),
('1/22/2015 12:00:00 AM')
<强>查询强>
;WITH CTE AS
(
SELECT DateColumn
,ROW_NUMBER() OVER (ORDER BY DateColumn) rn
FROM @Table
)
SELECT A.DateColumn AS DateColumn1
,B.DateColumn AS DateColumn2
FROM CTE A
LEFT JOIN CTE B ON A.rn = B.rn - 1
<强>结果强>
╔═════════════════════════╦═════════════════════════╗
║ DateColumn1 ║ DateColumn2 ║
╠═════════════════════════╬═════════════════════════╣
║ 2014-07-11 00:00:00.000 ║ 2014-07-31 00:00:00.000 ║
║ 2014-07-31 00:00:00.000 ║ 2014-08-21 00:00:00.000 ║
║ 2014-08-21 00:00:00.000 ║ 2014-09-19 00:00:00.000 ║
║ 2014-09-19 00:00:00.000 ║ 2014-11-20 00:00:00.000 ║
║ 2014-11-20 00:00:00.000 ║ 2014-12-18 00:00:00.000 ║
║ 2014-12-18 00:00:00.000 ║ 2015-01-22 00:00:00.000 ║
║ 2015-01-22 00:00:00.000 ║ NULL ║
╚═════════════════════════╩═════════════════════════╝
答案 1 :(得分:0)
DECLARE @Table TABLE (DateColumn DATETIME)
INSERT INTO @Table VALUES
('7/11/2014 12:00:00 AM'),
('7/31/2014 12:00:00 AM'),
('8/21/2014 12:00:00 AM'),
('9/19/2014 12:00:00 AM'),
('11/20/2014 12:00:00 AM'),
('12/18/2014 12:00:00 AM'),
('1/22/2015 12:00:00 AM')
;WITH CTE AS (
select DateColumn,ROW_NUMBER()OVER (ORDER BY DATECOLUMN)RN from @Table
)
select DATECOLUMN, DATECOLUMN As NewColumn from CTE WHERE RN > 1
UNION ALL
select DATECOLUMN,CASE WHEN RN = 1 then NULL ELSE ' ' END As NewColumn
from CTE WHERE RN = 1
ORDER BY DATECOLUMN