1

这是我的代码:

select row_number() over (order by cte3.update desc) as row_num,

            (select cte3.update from last_two_items 
             where idOrder = 1 and 
             cte3.toy_id = toy_id
            ) as update,

            cte3.price_previous as price_previous,
            cte3.price_current as price_current,
            cte3.id as id,
            cte3.toy_id as toy_id

    from last_two_items as cte3
    where idOrder = 2

我有一个名为 last_two_items 的临时表。这个临时表有几列:旧价格、新价格、更新日期、idOrder 等。

它看起来像这样:

old_price   new_price    date of update             idOrder         toy_id
0           0.16         2013-08-06 10:03:41.700    1               123
0.16        0.08         2013-08-06 10:02:28.850    2               123

作为查询的结果,我想从 idOrder 为 2 的记录中获取旧价格和新价格,但从 idOrder = 1 的记录中获取更新日期。两个记录的玩具相同。

但是,使用我拥有的代码(此问题开头的代码),我只能获得 idOrder = 2 的记录。

这个怎么做?

4

2 回答 2

2

我认为问题在于你没有给你的桌子一个正确的标签,这会造成一些混乱。尝试这个:

select row_number() over (order by cte3.update desc) as row_num,

        (select innerQuery.update from last_two_items as innerQuery
         where innerQuery.idOrder = 1 and 
         innerQuery.toy_id = cte3.toy_id
        ) as update,

        cte3.price_previous as price_previous,
        cte3.price_current as price_current,
        cte3.id as id,
        cte3.toy_id as toy_id

from last_two_items as cte3
where idOrder = 2
于 2013-08-12T09:04:37.810 回答
0

尽管它正在工作,但我建议使用其他方法:

select lti2.old_price, lti2.new_price, lti1.date_of_update
from last_two_items lti1
left join last_two_items lti2
where lti1.idOrder = 1 and lti2.idOrder = 2 

没有子选择相当容易。

于 2013-08-12T09:32:59.807 回答