跨列和行查找每个值的最新时间戳
Finding latest timestamp per value across columns and rows
我有一个数据库 table,其中的行如
Id | s1 | ts1 | s2 | ts2 | ... | s6 | ts6
其中 ID 是行的非唯一标识符,将用于过滤初始数据集。字段 s1
到 s6
包含值,列 ts1
到 ts6
包含它们的时间戳。我需要找到每个“s”值的最新(或第一个)时间戳。 “s”值不是唯一的,相同的值可能出现在任何“s”列中。
我还没有尝试过任何东西,因为我不知道如何将这些列变成行。如果我知道,那么我可能会找到每个值的最新(具有 max 函数)。但是如何将它们变成行呢?我知道有 PIVOT
功能,但我不完全确定如何使用它以及如何将这些列变成单个“s”和“ts”列。
编辑:
示例数据集:
ID s1 ts1 s2 ts2 s3 ts3 s4 ts4 s5 ts5 s6 ts6
123456 aa 1647456495 ab 1647456495 ac 1647456495 ad 1647456495 ae 1647456495 af 1647456495
123456 ax 1647456495 aa 1647456495 af 1647456495 al 1647456495 ai 1647456495 as 1647456495
123456 ab 1647456495 aa 1647456495 ad 1647456495 ac 1647456495 ae 1647456495 af 1647456495
示例输出:
s_value ts_value
aa 1647456495
ab 1647456495
af 1647456495
...
ax 1647456495
我在示例中使用了相同的 unix 纪元时间戳,但这正是数据的样子。每个数据集大约有 20-100k 行,“s”字段有 10-30 个不同的值。不确定这是否相关。
感谢@Conor Cunningham MSFT 的建议,这将是一个很好的解决方案。我已经反驳,得到了预期的结果,并将其作为答案发布。
来源:
-- get the distinct values of 's' and 't' columns
select s1 as s_values, t1 as t_values into #temp_latest from test_tb
union
select s2, t2 from test_tb
union
select s3, t3 from test_tb
union
select s4, t4 from test_tb
union
select s5, t5 from test_tb
union
select s6, t6 from test_tb
-- to get the max t values for same s value
select s_values, max(t_values) t_values from #temp_latest
group by s_values
我有一个数据库 table,其中的行如
Id | s1 | ts1 | s2 | ts2 | ... | s6 | ts6
其中 ID 是行的非唯一标识符,将用于过滤初始数据集。字段 s1
到 s6
包含值,列 ts1
到 ts6
包含它们的时间戳。我需要找到每个“s”值的最新(或第一个)时间戳。 “s”值不是唯一的,相同的值可能出现在任何“s”列中。
我还没有尝试过任何东西,因为我不知道如何将这些列变成行。如果我知道,那么我可能会找到每个值的最新(具有 max 函数)。但是如何将它们变成行呢?我知道有 PIVOT
功能,但我不完全确定如何使用它以及如何将这些列变成单个“s”和“ts”列。
编辑:
示例数据集:
ID s1 ts1 s2 ts2 s3 ts3 s4 ts4 s5 ts5 s6 ts6
123456 aa 1647456495 ab 1647456495 ac 1647456495 ad 1647456495 ae 1647456495 af 1647456495
123456 ax 1647456495 aa 1647456495 af 1647456495 al 1647456495 ai 1647456495 as 1647456495
123456 ab 1647456495 aa 1647456495 ad 1647456495 ac 1647456495 ae 1647456495 af 1647456495
示例输出:
s_value ts_value
aa 1647456495
ab 1647456495
af 1647456495
...
ax 1647456495
我在示例中使用了相同的 unix 纪元时间戳,但这正是数据的样子。每个数据集大约有 20-100k 行,“s”字段有 10-30 个不同的值。不确定这是否相关。
感谢@Conor Cunningham MSFT 的建议,这将是一个很好的解决方案。我已经反驳,得到了预期的结果,并将其作为答案发布。
来源:
-- get the distinct values of 's' and 't' columns
select s1 as s_values, t1 as t_values into #temp_latest from test_tb
union
select s2, t2 from test_tb
union
select s3, t3 from test_tb
union
select s4, t4 from test_tb
union
select s5, t5 from test_tb
union
select s6, t6 from test_tb
-- to get the max t values for same s value
select s_values, max(t_values) t_values from #temp_latest
group by s_values