SQL SELECT基于几个条件的最后一个条目

时间:2017-04-05 07:09:07

标签: mysql sql conditional-statements

在我的情况下,我想为每对夫妇选择最后一条记录(company_id,product_id),只返回那些股票不是0的记录。

company_id  product_id    stock        date
    165         6           0       2017-01-09
    168         4         900000    2017-01-08
    165         6          1520     2017-01-07
    165         5        1200000    2017-01-06
    167         2           0       2017-01-05
    167         1        1401700    2017-01-04
    167         1        1450800    2017-01-03
    168         4           0       2017-01-02
    167         2        2360400    2017-01-01

在此示例中,表格为:

company_id  product_id    stock        date
    168         4         900000    2017-01-08
    165         5        1200000    2017-01-06
    167         1        1401700    2017-01-04

谢谢!

2 个答案:

答案 0 :(得分:3)

有一个子查询,返回每个company_id / product_id及其最后日期(库存非零。)JOIN,结果如下:

select t1.company_id, t1.product_id, t1.stock, t1.date
from tablename t1
join (select company_id, product_id, max(date) maxdate
      from tablename
      where stock <> 0 group by company_id, product_id) t2
  on  t1.company_id = t2.company_id
  and t1.product_id = t2.product_id
  and t1.date = t2.maxdate
where stock <> 0 

答案 1 :(得分:2)

  • 使用子查询获取每个公司/产品的最长日期。
  • 然后加入返回源表并过滤掉零库存行。

查询

select  t1.company_id, t1.product_id, t1.stock, t1.date
from    tablename t1
        inner join (
            select  company_id, product_id, max(date) maxdate
            from    tablename
            group by company_id, product_id) t2
        on  t1.company_id = t2.company_id
        and t1.product_id = t2.product_id
        and t1.date = t2.maxdate
where t1.stock <> 0