mysql-计算日期间销售利润

7hiiyaii  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(388)

我有一张这样的table:

+--------+---------------------+-------+--------+-----------+
| PartNo | Date                | Inv   | Retail | Wholesale |
+--------+---------------------+-------+--------+-----------+
| 1      | 2018-05-12 00:00:00 | 15    | $100   | $90       |
| 2      | 2018-05-12 00:00:00 | 20    | $200   | $150      |
| 3      | 2018-05-12 00:00:00 | 25    | $300   | $200      |
| 1      | 2018-05-13 00:00:00 | 10    | $95    | $90       |
| 2      | 2018-05-14 00:00:00 | 15    | $200   | $150      |
| 3      | 2018-05-14 00:00:00 | 20    | $300   | $200      |
+--------+---------------------+-------+--------+-----------+

我希望mysql查询的结果如下:

+--------+------+--------+
| PartNo | Sold | Profit |
+--------+------+--------+
| 1      | 5    | $25    |
| 2      | 5    | $250   |
| 3      | 5    | $500   |
+--------+------+--------+

我需要按partno分组,同时计算一个日期范围内的总利润和利润之间的差异。
单位利润的计算方法是从日期范围最后一天(或记录)的零售额中减去批发额。
我觉得这应该是容易的,但在日期范围的差异是混淆我和处理的日期范围内的记录,不开始或结束日期范围输入完全失去我。
任何帮助都将不胜感激。
谢谢您。

cig3rfwq

cig3rfwq1#

您可以在期初和期末查看情况,如果没有发现期初情况,则假设没有库存。如果没有发现最终情况,这意味着在此期间没有销售。
例如,开始的时段 2018-05-13 和结束 2018-05-14 :

select  parts.PartNo
,       coalesce(FirstSale.Total, 0) - coalesce(LastSale.Total, FirstSale.Total, 0) as Sold
,       (coalesce(FirstSale.Total, 0) - coalesce(LastSale.Total, FirstSale.Total, 0)) *
           coalesce(LastSale.Retail - LastSale.Wholesale, 0) as Profit
from    (
        select  PartNo
        ,       max(case when Date < '2018-05-13' then Date end) as FirstEntry
        ,       max(case when Date <= '2018-05-14' then Date end) as LastEntry
        from    Sales
        group by
                PartNo
        ) parts
left join    
        Sales FirstSale
on      FirstSale.PartNo = parts.PartNo
        and FirstSale.Date = parts.FirstEntry
left join    
        Sales LastSale
on      LastSale.PartNo = parts.PartNo
        and LastSale.Date = parts.LastEntry

例如sql fiddle。

xpcnnkqh

xpcnnkqh2#

SELECT c.partno as partno,MAX(c.inv)-MIN(c.inv) as sold,SUM(CASE WHEN c.date = c.last_date THEN profit else 0 END)*(MAX(c.inv)-MIN(c.inv)) as profit
FROM (SELECT partno,date,inv,retail-wholesale as profit,MAX(date) OVER (partition by partno) AS last_date FROM test1)c
GROUP BY c.partno
ORDER BY c.partno;

使用window函数,首先添加一个新列来跟踪每个partno的最大日期。所以from中的内部查询将生成这样的行,其中一列添加到原始数据集中,

| 1      | 2018-05-12 00:00:00 | 15    | $100   | $90       |**2018-05-13 00:00:00**|

突出显示的字段是添加到数据集的字段,它是该零件号日期范围内的最后一个日期!
现在从这个结果中,我们可以通过检查date列与我们添加的新列相等的行来提取利润,这实际上是通过从零售中减去批发,再乘以售出的商品来计算最后一个日期的利润。
ps:销售商品的逻辑是按零件号分组,并从最大值(inv)中减去最小值(inv)
链接到sql fiddle

相关问题