MySql获取具有最新日期的行

时间:2016-10-14 14:14:08

标签: mysql

以下是代码:

SELECT        tblitem.strItemCode, tblitem.strItemName, tblitemunit.strItemUnitName, tblvendor.strVendName, MAX(tblitemprice.dtmItemPasOf) AS Expr1, 
                         tblitemprice.dblItemPAmount
FROM            tblclassification INNER JOIN
                         tblitem ON tblclassification.strClasCode = tblitem.strItemClasCode INNER JOIN
                         tblitemprice ON tblitem.strItemCode = tblitemprice.strItemPItemCode INNER JOIN
                         tblitemunit ON tblitemprice.strItemPItemUnitCode = tblitemunit.strItemUnitCode INNER JOIN
                         tblvendor ON tblclassification.strClasCode = tblvendor.strVendClasCode AND tblitemprice.strItemPVendCode = tblvendor.strVendCode AND tblitem.deleted_at IS NULL
GROUP BY tblitem.strItemCode, tblitem.strItemName, tblitemunit.strItemUnitName, tblvendor.strVendName, tblitemprice.dblItemPAmount

以下是结果:

CODE     NAME        UNIT    VENDOR          DATE            PRICE

ITEM101-Fudgee Bar-Piece-Imus Palengke 10/9/20165:03:32AM - 6.5

ITEM102-Yum Burger-Box-Jollibee Lumina Mall-10/9/2016 6:13:27 AM  -    2500

ITEM102-Yum Burger-Piece-Jollibee Lumina Mall-10/9/2016 4:42:28 AM  -  30
ITEM102-Yum Burger-Piece-Jollibee Lumina Mall-10/13/2016 12:37:31 PM-  35

ITEM102-Yum Burger  Piece   Jollibee Lumina Mall    10/14/2016 10:05:44 PM  40

我想要的是只获取最新价格的行。有谁可以帮助我吗。

我想要获取Item101,而只想获取最后一行到ITEM102。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您正在寻找最后更新的行价。这样做很容易:

  1. 按相反的时间戳以相反的顺序(ORDER BY <FIELD_NAME> DESC)订购数据。根据我从您的查询和结果中收集的内容,Expr1是给定价格的最新日期。
  2. 只选择一个元素(LIMIT 1)。由于您的数据已按逆时间顺序排序,因此您一定要选择最新的数据。
  3. 那个SQL将是

    SELECT        tblitem.strItemCode, tblitem.strItemName, tblitemunit.strItemUnitName, tblvendor.strVendName, MAX(tblitemprice.dtmItemPasOf) AS Expr1, 
                             tblitemprice.dblItemPAmount
    FROM            tblclassification INNER JOIN
                             tblitem ON tblclassification.strClasCode = tblitem.strItemClasCode INNER JOIN
                             tblitemprice ON tblitem.strItemCode = tblitemprice.strItemPItemCode INNER JOIN
                             tblitemunit ON tblitemprice.strItemPItemUnitCode = tblitemunit.strItemUnitCode INNER JOIN
                             tblvendor ON tblclassification.strClasCode = tblvendor.strVendClasCode AND tblitemprice.strItemPVendCode = tblvendor.strVendCode AND tblitem.deleted_at IS NULL
    GROUP BY tblitem.strItemCode, tblitem.strItemName, tblitemunit.strItemUnitName, tblvendor.strVendName, tblitemprice.dblItemPAmount
    ORDER BY Expr1 DESC
    LIMIT 1
    

    尝试一下!