php - SQL 查询根据所选日期查找值,但如果所选日期没有值,则会查找最新值

标签 php mysql sql greatest-n-per-group

我想获取当前日期的分支值,但如果当前日期没有值,则获取其最新读数的值。

例如,所选日期为 2013 年 9 月 29 日。

我有三个分支机构。

其中两个分支机构的销售值(value)截至 2013 年 9 月 29 日。

一个分支没有编码值,但该分支的最新值日期为 2013 年 8 月 30 日。

换句话说,

Branch 1 - Sep 29 - value is 150
Branch 2 - Sep 29 - value is 150
Branch 3 - Sep 29 - value is 0

我不能只做 150 + 150 + 0 = 300

我要做的是:

Branch 1 - Sep 29 - value is 150
Branch 2 - Sep 29 - value is 150
Branch 3 - Sep 29 - value is 0, so find the latest reading, system finds August 30 with value 250.

所以现在我可以做 150 + 150 + 250 = 550

目前,我有以下 SQL 查询:

SELECT 
    user_id, product_code, uom, inventory_date, account_id, branch_id, beginning_inventory 

FROM 
    inventory_mgmt_uploads 

WHERE 
    user_id = '137'
    AND product_code = 'GRO_AL'
    AND uom = 'box'
    AND account_id = '3'
    AND inventory_date <= '2013-09-29'

ORDER BY
    inventory_date

上面查询的结果是:

enter image description here

现在我想要实现的是这样的结果:

enter image description here

我尝试过的是这个查询:

SELECT 
    user_id, product_code, uom, inventory_date, account_id, branch_id, beginning_inventory 

FROM 
    inventory_mgmt_uploads 

WHERE 
    user_id = '137'
    AND product_code = 'GRO_AL'
    AND uom = 'box'
    AND account_id = '3'
    AND inventory_date <= '2013-09-29'

GROUP BY
    branch_id

ORDER BY
    inventory_date

但它给了我:

enter image description here

即使我尝试按branch_id desc或inventory_date desc进行订购,我仍然无法获得所需的输出。 任何想法什么是正确的查询? TIA!

最佳答案

您也可以尝试一下:

SELECT a.USER_ID, a.PRODUCT_CODE, a.UOM, MAX(a.INVENTORY_DATE), a.ACCOUNT_ID, a.BRANCH_ID, (
  SELECT BEGINNING_INVENTORY FROM test 
  WHERE user_id = a.user_id
  AND product_code = a.product_code
  AND uom = a.uom
  AND inventory_date = MAX(a.inventory_date)
  AND account_id = a.account_id
  AND branch_id = a.branch_id
) as BEGINNING_INVENTORY
FROM test as a
WHERE a.INVENTORY_DATE <= '2013-09-29'
GROUP BY a.USER_ID, a.product_code, a.uom, a.account_id, a.branch_id

Sashi Kant 提到的查询工作正常,因为您有顺序数据(beginning_inventory 随着日期而减少)。如果数据被打乱,上述方法将无法给出正确的数据。

关于php - SQL 查询根据所选日期查找值,但如果所选日期没有值,则会查找最新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19312185/

相关文章:

php - 通过纯枚举实现 JsonSerialized

javascript - jQuery Ajax 脚本相互淘汰

php - 在 laravel 5.2 的路径中找不到文件

javascript - 当新的 mysql 数据进来时点击更新 javascript 数组

java - 无法执行查询

sql - 如何从 T-SQL 脚本调用 FoxPro 存储过程

php - 连接 Facebook Graph API 时 ElasticBeanstalk for PHP 上的 504 网关超时

mysql - Ecto 为 Mysql/Mariadb 创建唯一索引失败

mysql - REGEXP 使用 MySQL 匹配字符串中的任一关键字

MySQL 1064 : You have an error in your SQL syntax