SQL:Join表的上次日期

时间:2017-05-05 03:29:09

标签: sql greatest-n-per-group

表:

msub - > id,receive

msublist - > id,sub_id,item_id,qty

我试试。

select a.sub_id
, a.item_id
, a.qty
, b.id
, b.receive_date
from msublist a 
 join (select x.id
, x.receive_date
from msub x
where x.receive_date = (select max(x1.receive_date)
                       from msub x1
                       where x1.id = x.id)) b
on (a.sub_id = b.id)
order by a.item_id,b.receive_date desc

它没有工作。我想成为item_id的最后日期

3 个答案:

答案 0 :(得分:0)

试试这个: -

select a.sub_id
, a.item_id
, a.qty
, b.id
, b.receive_date
from msublist a 
inner join
(
 Select a.sub_id,b.id,a.item_id, max(b.receive_dt) as receive_date
 from
 msublist a
 inner join
 msub b
 on a.sub_id=b.id
 group by a.sub_id,b.id,a.item_id
) b
on a.sub_id=b.sub_id and a.item_id=b.item_id 

如果您有任何问题,请告诉我

答案 1 :(得分:0)

试试这个

   select   a.sub_id
        , a.item_id
        , a.qty
        , b.id
        , b.receive_date
   from msublist a 
   join (select x.id
        , x.receive_date
        from msub x
        where x.receive_date = (select max(x1.receive_date)
                               from msub x1
                               )) b
    on a.sub_id = b.id
    order by a.item_id,b.receive_date desc

这是你要找的那个吗?

答案 2 :(得分:0)

请尝试以下方法......

SELECT msublist.sub_id AS msub_id,
       msublist.item_id AS item_id,
       msublist.qty AS qty,
       msublist.id AS msublist_id,
       mostRecentDate AS receive_date
FROM msub
JOIN msublist ON msub.id = msublist.sub_id
JOIN ( SELECT item_id,
              MAX( receive_date ) AS mostRecentDate
       FROM msub
       JOIN msublist ON msub.id = msublist.sub_id
       GROUP BY item_id
     ) AS mostRecentDateFinder ON msublist.item_id = mostRecentDateFinder.item_id
                              AND msub.receive_date = mostRecentDateFinder.mostRecentDate
ORDER BY item_id;

此语句以在INNER JOINmsub之间执行msublist的子查询开始,然后按item_id对结果进行分组。然后,对于每个组(即每个item_id值),它会找到相应receive_date值的最大值。

然后,生成的列表在它与数据集之间执行了INNER JOIN,这些数据集来自加入msubmsublist的公共值,其方式是只有来自{的那些行保留msubmsublist匹配组合的{1}} / item_id数据集。

然后,生成的数据集按mostRecentDate的值进行排序。

最后,返回所需的字段。

如果您有任何问题或意见,请随时发表评论。