查询从一个记录中获取价格,从另一个记录获取日期

时间:2013-08-12 08:59:36

标签: sql-server tsql

这是我的代码:

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的记录。

怎么做?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 

没有次选的相当简单的事情。