我有以下问题:我有一个包含数千行且具有相同时间戳的表。我需要每一行都有一个唯一的时间戳,可以在时间序列数据库中输入。所以我想知道是否有人对如何通过查询使DATETIME
字段唯一有任何想法。
这就是我正在使用的:
2015-09-17 00:00:00.000
2015-09-17 00:00:00.000
2015-09-17 00:00:00.000
2015-09-17 00:00:00.000
2015-09-17 00:00:00.000
2015-09-17 00:00:00.000
我们已经想到了添加到毫秒的唯一ID,但.1和.10将是同一时间。我希望保持日期不变,并尽可能操纵时间以使其独一无二。此查询将返回10,000行,并且它们都具有相同的时间戳,并且它们都必须以某种方式变得唯一。
答案 0 :(得分:0)
以此片段为例。它紧密递增源日期毫秒,这意味着它使用DATETIME
毫秒精度(.000,.003,.007)的最小增量。
CREATE TABLE #tt(teh_date DATETIME, teh_seq INT IDENTITY(1,1));
INSERT INTO #tt(teh_date)VALUES
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000'),
('20150917 00:00:00.000');
;WITH cte AS (
SELECT
*,
rn=ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
--rn=ROW_NUMBER() OVER(ORDER BY teh_seq) --> use this line instead if you have one or more columns you can sort on
FROM
#tt
)
SELECT
teh_date=DATEADD(MS,(CASE (rn-1)%3 WHEN 0 THEN 0 WHEN 1 THEN 3 WHEN 2 THEN 7 END)+((rn-1)/3)*10,teh_date)
FROM
cte
ORDER BY
teh_date;
/* -> use this UPDATE statement instead of the above SELECT if you want to update the source table
UPDATE
cte
SET
teh_date=DATEADD(MS,(CASE (rn-1)%3 WHEN 0 THEN 0 WHEN 1 THEN 3 WHEN 2 THEN 7 END)+((rn-1)/3)*10,teh_date);
SELECT teh_date FROM #tt ORDER BY teh_seq;
*/
DROP TABLE #tt;
结果:
+-------------------------+
| teh_date |
+-------------------------+
| 2015-09-17 00:00:00.000 |
| 2015-09-17 00:00:00.003 |
| 2015-09-17 00:00:00.007 |
| 2015-09-17 00:00:00.010 |
| 2015-09-17 00:00:00.013 |
| 2015-09-17 00:00:00.017 |
| 2015-09-17 00:00:00.020 |
| 2015-09-17 00:00:00.023 |
| 2015-09-17 00:00:00.027 |
| 2015-09-17 00:00:00.030 |
| 2015-09-17 00:00:00.033 |
| 2015-09-17 00:00:00.037 |
| 2015-09-17 00:00:00.040 |
| 2015-09-17 00:00:00.043 |
+-------------------------+