mysql - 计算每个项目和日期范围内的每个月库存中的项目数量 - mysql

标签 mysql sql group-by

我有一个包含 3 列的 T1 表:ProductBrandPurchasedDateSoldDateProductBrand 表示产品的品牌。 PurchasedDate 包含我们购买产品的日期(格式为 yyyy-mm),SoldDate 包含我们出售该产品的日期(同样为 yyyy-mm)。例如:

ProductBrand  PurchasedDate  SoldDate
----------------------------------
Apple          2015-03      2015-05
Samsung        2014-01      2015-03
Sony           2016-02      2016-05 
Sony           2013-01      2013-08 
Apple          2015-05      2015-10 
LG             2011-02      2014-06 
Samsung        2017-02      2017-04 
LG             2016-01      2016-06 
LG             2018-06      2019-01

我想要一个表格来计算每个品牌和每个月(2010-01 年和 2019-12 年之间)库存中这个特定月份我有多少这个特定品牌的产品。也就是说,在这个例子中,我有两个 Apple 产品。第一个留在 2015-03 和 2015-06 之间的库存中,第二个留在 2015-04 和 2015-08 之间的库存中。所以我希望有一个表:

ProductBrand  YearMonthDate  NitemsInventory
------------  ------------   -------------------
Apple         2010-01               0
Apple         2010-02               0
...            ...                 ... 
Apple         2015-03               1
Apple         2015-04               2
Apple         2015-05               2
Apple         2015-06               2
Apple         2015-07               1
Apple         2015-08               1
Apple         2015-09               0
...            ...                 ...
Apple         2019-12               0

在同一张表中,我希望所有品牌都采用与 Apple 相同的方式。因此,如果我们有 n 个不同的品牌,而 t 是(2010-01 和 2019-12)之间的月数,则最终数组将有 n 次 t 行。换句话说,我想查看每个月我在每个品牌的库存中拥有的商品数量。

我正在使用 mysql,我想我已经尝试对 T1 的 ProductBrand 列进行分组。然而,这并没有达到我的预期。

最佳答案

我们可以用一些丑陋的大日历表来做到这一点:

SELECT
    t.ProductBrand,
    d.YearMonthDate,
    COUNT(t.ProductBrand) AS NitemsInventory
FROM
(
    SELECT DISTINCT ProductBrand FROM yourTable
) AS p
CROSS JOIN
(
    SELECT '2010-01' AS YearMonthDate UNION ALL
    SELECT '2010-02' UNION ALL
    SELECT '2010-03' UNION ALL
    ...
    SELECT '2015-03' UNION ALL
    SELECT '2015-04' UNION ALL
    ...
    SELECT '2019-12'
) AS d
LEFT JOIN yourTable t
    ON d.YearMonthDate BETWEEN t.PurchasedDate AND t.SoldDate AND
       p.ProductBrand = t.ProductBrand
WHERE
    t.productBrand IS NOT NULL
GROUP BY
    t.ProductBrand,
    d.YearMonthDate;

这是一个展示查询操作的演示:

Demo

关于mysql - 计算每个项目和日期范围内的每个月库存中的项目数量 - mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55631342/

相关文章:

sql - SSIS - 派生列

MYSQL 选择日期早于日期时间的行

mysql在where子句中重复子查询

MySql - 进一步查询优化SELECT WHERE IN

python - 如何找出 pandas groupby 对象中唯一行的数量?

r - 通过对 r 中的另一列进行分组来求 n 行的平均值

SQL按列排序并同时按另一列分组

php - 在 Freebase 中检索/存储所有相关的 Actor

mysql - 警告 : ? : (mysql. W002)

mysql - 查询返回空结果但数据存在