使用重复键在表中查找具有不同键的最新记录

时间:2018-01-13 00:27:07

标签: sql amazon-redshift

我一直在尝试在包含重复键的表的不同键的表中找到最新记录,如下表所示:

 id        |   user        |   timestamp
-----------+---------------+-------------------------
 aaa       | user_5       | 2015-01-28 22:28:55.111
 aaa       | user_6       | 2015-01-29 22:28:55.111
 aaa       | user_1       | 2015-01-24 22:28:55.111
 aaa       | user_4       | 2015-01-27 22:28:55.111
 aaa       | user_8       | 2015-01-31 22:28:55.111
 aaa       | user_2       | 2015-01-25 22:28:55.111
 aaa       | user_0       | 2015-01-23 22:28:55.111
 aaa       | user_9       | 2015-01-22 22:28:55.111
 zzz       | user_new     | 2015-01-22 22:28:55.111
 aaa       | user_3       | 2015-01-26 22:28:55.111
 aaa       | user_7       | 2015-01-30 22:28:55.111

预期的结果是

 id        |   user        |   timestamp
-----------+---------------+-------------------------
 aaa       | user_8       | 2015-01-31 22:28:55.111
 zzz       | user_new     | 2015-01-22 22:28:55.111

我无法想出得到理想的结果。请帮忙

2 个答案:

答案 0 :(得分:1)

select id, user, timestamp from (select t.*, row_number() over (partition by id order by timestamp desc) as seqnum from t ) t where seqnum = 1; 是一个简单的解决方案:

// serverside js file

import Web3 from 'web3';

if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider);
} else {
  var net = require('net');
  var web3 = new Web3('/home/xxYourHomeFolderxx/.ethereum/geth.ipc', net);
};

  // set the default account
  web3.eth.defaultAccount = '0x123..............';

  web3.eth.coinbase = '0x123..............';

  web3.eth.getAccounts(function(err, acc) {
    _.each(acc, function(e) {
      web3.eth.getBalance(e, function (error, result) {
        if (!error) {
          console.log(e + ': ' + result);
        };
      });
    });
  });

答案 1 :(得分:0)

您可以尝试此查询!

SELECT 
       id          , 
       user        , 
       timestamp 
FROM 
       [table name]
WHERE 
       timestamp=(SELECT MAX(timestamp) FROM [table name])
GROUP BY 
       id