想知道是否有一种方法可以获得与出口日期相同的商品的库存案例列的总和?
更新了fiddle和一些相关数据:
https://www.db-fiddle.com/f/szc1ftj3zgec24gsyp6ad4/4
预期结果如下:
这是使用的查询
SELECT
st.product_code,
st.date_of_export,
st.best_before_date,
st.stock_case,
(
SELECT
SUM(st2.stock_case)
FROM
stock_tracking AS st2
WHERE
st2.product_code IN ('MGN003')
AND MONTH(st2.date_of_export) IN (07)
AND YEAR(st2.date_of_export) IN (2018)
AND st2.stock_case != 0
) AS total
FROM
stock_tracking st
WHERE
product_code IN ('MGN003')
AND MONTH(st.date_of_export) IN (07)
AND YEAR(st.date_of_export) IN (2018)
AND stock_case != 0
我的结果呢
希望有一个16,16,16,19等等,在另一个例子中,我使用了这样的子查询
SELECT
d.products_name,
stock_case,
st.date_of_export,
st.best_before_date,
st.product_code,
(SELECT
SUM(st2.stock_case)
FROM
stock_tracking AS st2
WHERE
DATE(st2.date_of_export) = (SELECT
DATE(tmp.last_update)
FROM
(SELECT
date_of_export AS last_update
FROM
stock_tracking
ORDER BY date_of_export DESC
LIMIT 1) AS tmp
WHERE
product_code = 'MGN003')) AS total
FROM
stock_tracking st
LEFT JOIN
products AS p ON p.products_model = st.product_code
LEFT JOIN
products_description AS d ON d.products_id = p.products_id
WHERE
product_code = 'MGN003'
AND d.language_id = 2
AND DATE(st.date_of_export) = (SELECT
DATE(tmp.last_update)
FROM
(SELECT
date_of_export AS last_update
FROM
stock_tracking AS st
ORDER BY date_of_export DESC
LIMIT 1) AS tmp)
结果如下:
2条答案
按热度按时间wribegjk1#
您可以将子查询写入
sum(stock_case)
由date_of_export
,那么self join
在Date
,则可以得到预期的结果。sqlfiddle公司
iklwldmw2#
不给你确切的答案:你应该朝着以下方向思考:
或者
因此,查找分组方式和不同的工作方式:-)