我有一个带有列的表
Account number (number)
Account Status(Number)
Datetime(text)
某些帐户重复使用相同的时间戳记
我需要获取具有相同时间戳的同一帐户的数据重复到新列的帐户状态(新帐户状态)
Account_Number Account Status Timestamp
7856277 5 9155070519
4527882 5 1045225522
7856277 1 9155070519
我想
Account_Number Account Status Timestamp new account Status
7856277 5 9155070519 1
答案 0 :(得分:0)
您将要使用帐号作为链接列将表与其自身连接。考虑下面的查询(其中o
是较旧的记录,n
是较新的记录)
SELECT o.account_number, o.account_status, n.timestamp, n.account_status "new account status"
FROM table o join table n on (o.account_number = n.account_number)
WHERE n.timestamp>o.timestamp
答案 1 :(得分:0)
SQL表表示无序集。因此,除非列指定顺序,否则没有“新”或“旧”。您似乎没有这样的专栏。
但是您可以使用聚合将结果单行显示:
select Account_Number, Timestamp,
min(AccountStatus) as status_min,
max(AccountStatus) as status_max
from t
group by Account_Number, Timestamp
having count(*) > 1;
答案 2 :(得分:0)
您需要自我加入:
SELECT
t.account_number, t.account_status, t.timestamp,
tt.account_status new_account_status
FROM tablename t INNER JOIN tablename tt
ON
tt.account_number = t.account_number AND
tt.timestamp = t.timestamp AND
tt.account_status < t.account_status