使用2个不同的表并获取最新/最新值

时间:2013-07-11 17:03:41

标签: sql sql-server group-by max

在Microsoft SQL中挣扎了几个小时。

我有2张桌子。

Table1
ID | STOCK | STATUS
-----------------------------
1  | 1     | Out
2  | 1     | In
3  | 1     | Out
4  | 2     | Out
5  | 2     | In

Table2
ID | DATE
---------------
1  | 2013-07-01
2  | 2013-07-02
3  | 2013-07-03
4  | 2013-07-01
5  | 2013-07-02

我希望使用最新的DATE和STATUS

获取最新的STOCK

- >结果必须是

结果表

ID| STOCK | STATUS | DATE
-------------------------------
3 | 1     | Out    | 2013-07-03
5 | 2     | In     | 2013-07-02

我做了以下事情:

SELECT Table1.*, Table2.* FROM Table1, Table2 WHERE Table1.ID=Table2.ID

这会加入表格但会提供所有5条记录。所以我想我会像{/ p>那样使用MAX()函数

SELECT Table1.*, MAX(Table2.ID),Table2.Date  FROM Table1, Table2 WHERE Table1.ID=Table2.ID GROUP BY Table2.Date

但这不会在查询窗口中运行。

2 个答案:

答案 0 :(得分:1)

SELECT t1.id, t1.stock, t1.status, t5.mdate
FROM Table1 t1
inner join Table2 t2 on t1.id = t2.id
inner join
(
   select t3.stock, max(t4.date) as mdate
   from table1 t3
   inner join Table2 t4 on t3.ID = t4.ID
   group by t3.stock
) t5 on t5.stock = t1.stock and t5.mdate = t2.date

SQLFiddle demo

答案 1 :(得分:0)

使用此:

Select t1.id,t1.stock,t1.status,t2.date
FROM Table1 as t1,Table2 as t2
Where t1.id=t2.id
Order By t2.date DESC
LIMIT 1