简体   繁体   English

我需要计算每个商品的日间销售,MTD和年初至今的销售

[英]I need to calculate day sale ,MTD and YTD sale for each item

I need to find MTD (Month to date) and YTD (Year to Date) sales value for each item. 我需要找到每个项目的MTD(本月至今)和YTD(本年迄今)销售值。 And, I have filter to entire data on which I need to find the sales report. 而且,我可以筛选出需要查找销售报告的全部数据。 Based on that date it should find the MTD and YTD sales. 根据该日期,应该可以找到MTD和YTD的销售额。 it should group the item by barcode. 它应该按条形码对项目进行分组。 Example: in my filter if i enter: 21th of August , I should find that day sales and MTD,YTD. 示例:如果输入以下内容,则在过滤器中:8月21日,我应该找到当天的销售额和MTD,YTD。

It is working fine with current date, but if i entire any date other than current date then there is difference in MTD and YTD 它可以与当前日期一起正常工作,但是如果我除当前日期以外的所有其他日期,则MTD和YTD会有差异

SELECT Barcode,
       SUM(CASE WHEN DATE = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), -1) THEN sales_amount ELSE 0 END) AS day_1,
       SUM(CASE
                WHEN MONTH(date) = (MONTH(GETDATE() - 1))
                 AND YEAR(date) = YEAR(GETDATE() - 1) THENsales_amount
                ELSE 0
           END) AS month_t,
       SUM(CASE
                WHEN MONTH(date) = (MONTH(GETDATE() - 1))
                 AND YEAR(date) = YEAR(GETDATE() - 1) - 1 THEN GL_TOTALTTC
                ELSE 0
           END) AS lastyear_tm,
FROM sale
WHERE type = 'FFO'
  AND store = 'AE001A'
  AND (DATE = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), -1)
    OR ((MONTH(date) = (MONTH(GETDATE() - 1))
     AND YEAR(date) = YEAR(GETDATE() - 1))
     OR (MONTH(date) = (MONTH(GETDATE() - 1))
     AND YEAR(date) = YEAR(GETDATE() - 1) - 1)))
GROUP BY barcode;

You can use conditional aggregation: 您可以使用条件聚合:

select bar_code,
       sum(case when date >= dateadd(day, -1, convert(date, getdate()) then sales_amount end) as yesterday,
       sum(case when month(date) = month(getdate()) and year(date) = year(getdate()) then sales_amount end) as mtd,
       sum(case when year(date) = year(getdate()) then sales_amount end) as ytd
from sale
where type = 'FFO' and store = 'AE001A' 
group by barcode;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM