SQL-如何对来自同一表的多个查询执行嵌套SELECT?

时间:2019-07-16 16:03:21

标签: sql postgresql select

我写了一个嵌套的选择查询,它工作正常。

select user_id, transaction_id, t_timestamp 
from (
    select *, row_number() over (partition by (user_id || '*' || transaction_id) order by f_time asc) rownum
    from transactionMetricsView
    where metric_1 in (select metric_value 
                       from main.metrics 
                       where metric_key = 'metric_type_1')
)
where rownum = 1

但是main.metrics表也有一个m_date字段,因此我需要检查日期是否在给定范围内。 但是我不确定如何正确实现它。

我认为它应该看起来像下面的查询,但是现在更像是伪代码。

select user_id, transaction_id, t_timestamp 
from (
     select *, row_number() over (partition by (user_id || '*' || transaction_id) order by f_time asc) rownum
     from transactionMetricsView
     where metric_1 in (select metric_value 
                        from main.metrics 
                        where metric_key = 'metric_type_1') 
         and (select m_date 
              from main.metrics between $startDate and $endDate)
)
where rownum = 1

1 个答案:

答案 0 :(得分:0)

这可能有效:

 select user_id, transaction_id, t_timestamp from (select *, row_number() over (partition by (user_id || '*' || transaction_id) order by f_time asc) rownum
 from transactionMetricsView
 where metric_1 in (select metric_value 
                    from main.metrics 
                    where metric_key = 'metric_type_1'
                      and m_date between $startDate and $endDate
                    )
  and rownum = 1