获取按日期分组的列的总和

nimxete2  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(366)

想知道是否有一种方法可以获得与出口日期相同的商品的库存案例列的总和?
更新了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)

结果如下:

wribegjk

wribegjk1#

您可以将子查询写入 sum(stock_case)date_of_export ,那么 self joinDate ,则可以得到预期的结果。

SELECT  
    s.product_name,
    s.date_of_export,
    s.best_before_date,
    s.product_code,
    s.stock_case,
    t.totle
FROM
    stock_tracking s
INNER JOIN
    (
        SELECT SUM(stock_case) totle,date_of_export dt
       FROM stock_tracking
       where   
        product_code = 'MGN003'
        AND MONTH(date_of_export) =07
        AND YEAR(date_of_export) =2018
        AND stock_case != 0
      GROUP BY date_of_export
    ) t on DATE_FORMAT(s.date_of_export, "%d-%m-%Y") = DATE_FORMAT(t.dt, "%d-%m-%Y")
where 
    s.product_code = 'MGN003'
AND MONTH(s.date_of_export) =07
AND YEAR(s.date_of_export) =2018
AND s.stock_case != 0

sqlfiddle公司

iklwldmw

iklwldmw2#

不给你确切的答案:你应该朝着以下方向思考:

SELECT SUM(column) FROM table WHERE ... GROUP BY date

或者

SELECT SUM(column), DISTINCT date FROM table WHERE ...

因此,查找分组方式和不同的工作方式:-)

相关问题