1

在 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 条记录。所以我想我会MAX()像这样使用这个功能

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

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

4

2 回答 2

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 演示

于 2013-07-11T17:19:38.060 回答
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
于 2013-07-11T17:07:53.190 回答