我有一个包含 3 列的表T1:ProductBrand、PurchasedDate、SoldDate。ProductBrand代表产品的品牌。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)之间的月数,则 end 数组将有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;
这是一个演示,显示了正在执行的查询:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句