根据季度计算月销售额

时间:2015-05-29 16:01:25

标签: sql sql-server

我需要计算某一季度的月销售额。

这是我计算上一季度的代码。

set @quarter = datepart(QQ, getdate()) - 1

if @quarter = 0 
    begin
    set @quarter = 4
    set @year = datepart(year, getdate()) -1
    end
else set @year = datepart(year, getdate())

以下是我计算整个季度平均月销售额的代码。

SELECT TOP 5 d.sdealer_name, COUNT(c.icontract_id) / 3 as 'AverageMonthlySales'
FROM dealers d 
INNER JOIN contracts c 
    ON c.sdealer_number = d.sdealer_number 
WHERE (d.sdealer_number NOT LIKE '%demo%' 
  AND d.sdealer_status in ('A', 'R') 
  AND c.sagent_number = @sagent_number
  AND c.sstatus in ('P', 'A', 'C', 'E') 
  AND c.iproduct_type_id in (4)
  AND DATEPART(QQ, c.dtcontract_sale_date) = @quarter 
  AND DATEPART(year, c.dtcontract_sale_date) = @year)
GROUP BY  d.sdealer_name
ORDER BY COUNT(distinct c.icontract_id) desc

如何计算给定季度的每月动态总销售量?

1 个答案:

答案 0 :(得分:0)

ctrl + h ...只需用月份替换季度datepart。有没有什么理由你没有尝试过?

set @month = datepart(month, getdate()) - 1

if @month = 0 
    begin
    set @month = 12
    set @year = datepart(year, getdate()) -1
    end
else set @year = datepart(year, getdate())

SELECT TOP 5 d.sdealer_name, COUNT(c.icontract_id) as 'AverageMonthlySales'
FROM dealers d 
INNER JOIN contracts c 
    ON c.sdealer_number = d.sdealer_number 
WHERE (d.sdealer_number NOT LIKE '%demo%' 
  AND d.sdealer_status in ('A', 'R') 
  AND c.sagent_number = @sagent_number
  AND c.sstatus in ('P', 'A', 'C', 'E') 
  AND c.iproduct_type_id in (4)
  AND DATEPART(month, c.dtcontract_sale_date) = @month 
  AND DATEPART(year, c.dtcontract_sale_date) = @year)
GROUP BY  d.sdealer_name
ORDER BY COUNT(distinct c.icontract_id) desc