如何从表中选择每一行,并按联接表中最“最近的(时间戳)”关联的行对其进行排序?

时间:2019-02-28 09:59:17

标签: sql postgresql greatest-n-per-group

我有一个quotes的桌子。每个报价都可以得到feedbacks(报价有很多反馈)。

我想选择*个引号(当然是不同的),并按照每个引号从反馈表降序的最近submitted_at日期开始对其排序:

https://www.db-fiddle.com/f/pHTQzkWMYND8CGJcAiu2JC/3

我玩过PARTITION子句,但没有成功。

db-fiddle示例中查询的预期结果为:

3   2017-03-24T00:00:00.000Z    Cata
1   2017-01-02T00:00:00.000Z    Radu
4   2017-04-20T00:00:00.000Z    David

3 个答案:

答案 0 :(得分:3)

您可以使用以下解决方案:

SELECT quotes.id, f.submitted_at, buyer_name
FROM quotes INNER JOIN (
    SELECT quote_id, MAX(submitted_at) AS submitted_at 
    FROM feedbacks 
    GROUP BY quote_id
) f ON quotes.id = f.quote_id
ORDER BY f.submitted_at DESC

演示: https://www.db-fiddle.com/f/pHTQzkWMYND8CGJcAiu2JC/4

答案 1 :(得分:0)

小提琴链接已更改,因此您需要在下方使用row_number()

select q.id,f.submitted_at, q.buyer_name from 
(
 select *,row_number()over(partition by quote_id order by submitted_at desc) rn
from feedbacks 
) f
join  quotes q on f.quote_id=q.id
where f.rn=1

demo link

id  submitted_at                buyer_name
1   2017-03-20T00:00:00.000Z    Radu
3   2017-04-25T00:00:00.000Z    Cata
4   2017-01-10T00:00:00.000Z    David

答案 2 :(得分:0)

您不必使用子查询,您的预期结果将很简单。

var { height } = Dimensions.get('window');
var box_count = 3;
var box_height = height / box_count;

class Dashboard extends PureComponent {

  static navigationOptions = {
    title: 'Chat',
    headerStyle: { backgroundColor: 'red' },
    headerTitleStyle: { color: 'green' },
  }

  render() {
    return (
      <View style={styles.container}>
            <View style={[styles.box, styles.box1]}>
              <Text style={{ fontSize: 40 }}>Active Leave</Text>
            </View>
            <View style={[styles.box, styles.box2]}>
              <Text style={{ fontSize: 40 }}>Upcoming Leave</Text>
            </View>
            <View style={[styles.box, styles.box3]}>
              <Text style={{ fontSize: 40 }}>Absent status</Text>
            </View>
        </View>
    );
  }
}

const styles = StyleSheet.create({

  box: {
    height: box_height,
    borderRadius:10,
    alignItems: 'center', 
    justifyContent: "center",
  },
  box1: {
    backgroundColor: '#2196F3'
  },
  box2: {
    backgroundColor: '#8BC34A'
  },
  box3: {
    backgroundColor: '#e3aa1a'
  }
});

export default Dashboard;