这是我的样本数据集
id thing datetime price
----|-----|------------|----------
1 | A | 04/03/2009 | 399
2 | B | 04/03/2009 | 244
5 | C | 04/03/2009 | 555
3 | D | 04/03/2009 | 300
4 | A | 03/03/2009 | 200
6 | B | 03/03/2009 | 500
7 | C | 24/12/2008 | 600
8 | D | 01/01/2009 | 700
9 | A | 01/03/2009 | 250
10 | B | 01/03/2009 | 400
11 | C | 12/12/2008 | 300
12 | D | 20/01/2008 | 600
我需要从最大日期到每行的最后价格获取所有行。返回行应该像
id thing datetime price last price
---|-----|------------|--------|-----------
1 | A | 04/03/2009 | 399 | 200
2 | B | 04/03/2009 | 244 | 500
5 | C | 04/03/2009 | 555 | 600
3 | D | 04/03/2009 | 300 | 700
我可以在单个Sql中获得这个吗?在sql语句和sqlalchemy中需要这个 Sry任何错误, 在此先感谢:)
答案 0 :(得分:0)
我认为窗口功能可以解决您的问题
select id, thing, datetime, price
from (
select id, thing, datetime, price, rank()over(order by datetime desc ) rk
from yourTable )
where rk = 1;
答案 1 :(得分:0)
这可能不是最好的方法,但它是SQL SERVER的解决方案,请查看
with MY_TABLE as(
SELECT 1 id, 'A' thing , cast('20090403' as date) datetime, 399 price UNION ALL
SELECT 2 , 'B' , '20090403' , 244 UNION ALL
SELECT 5 , 'C' , '20090403' , 555 UNION ALL
SELECT 3 , 'D' , '20090304' , 300 UNION ALL
SELECT 4 , 'A' , '20090303' , 200 UNION ALL
SELECT 6 , 'B' , '20090303' , 500 UNION ALL
SELECT 7 , 'C' , '20081224' , 600 UNION ALL
SELECT 8 , 'D' , '20090301' , 700 UNION ALL
SELECT 9 , 'A' , '20090301' , 250 UNION ALL
SELECT 10 , 'B' , '20090301' , 400 UNION ALL
SELECT 11 , 'C' , '20081212' , 300 UNION ALL
SELECT 12 , 'D' , '20080120' , 600
)
SELECT id,
t1.thing,
DATETIME,
Y.price
FROM MY_TABLE t1
INNER JOIN (SELECT thing,price,rank()over(partition by thing order by datetime desc) as last_price
from MY_TABLE) as Y on Y.thing= t1.thing and Y.last_price =2
WHERE datetime = (SELECT MAX(datetime)
FROM MY_TABLE t2
WHERE t1.thing = t2.thing)