0

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

例如,选择的日期是 2013 年 9 月 29 日。

我有三个分支。

其中两个分支机构的销售额为 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

上面查询的结果是:

在此处输入图像描述

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

在此处输入图像描述

我试过的是这个查询:

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

但它给了我:

在此处输入图像描述

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

4

2 回答 2

0

尝试这个::

Select * from inventory_mgmt_uploads outerimu 
INNER JOIN 
  (  SELECT 
        user_id, MIN(inventory_date) as minInvent, branch_id as Bid, MIN(beginning_inventory) as Binvent

    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
) as tempTab
    on (tempTab.user_id = outerimu.user_id and tempTab.minInvent=outerimu.inventory_date AND tempTab.Binvent =outerimu.beginning_inventory and tempTab.Bid= outerimu.branch_id)
    ORDER BY
    inventory_date
于 2013-10-11T07:10:44.213 回答
0

你也可以试试这个:

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 随日期减少)。如果数据被打乱,上述方法不会给出正确的数据。

于 2013-10-11T07:31:24.110 回答