根据过去三个月的销售额计算不同的客户

时间:2014-07-06 07:50:02

标签: sql sql-server-2008 tsql

我需要根据过去三个月的销售情况,每月统计不同的客户。

通过添加当前月份客户计数并将最近三个月的客户添加到计数中来显示结果,如下所示:

  • 在APRIL月份,不同的客户数量(APRIL + MARCH + FEBRUARY)
  • 在5月份,不同的客户数量为(MAY + APRIL + MARCH)
  • 在6月份,不同的客户数量(6月+ 5月+ 4月)
  • 在7月份,不同的客户数量(7月+ 6月+ 5月)

这是我试过的:

SELECT  MonNumber = MONTH(h.Invoicedate) ,
            YearNumber = YEAR(h.Invoicedate) ,
            PartyCount = ( SELECT   COUNT(DISTINCT s.CustomerID)
                           FROM     salesdata s
                           WHERE    s.Invoicedate BETWEEN DATEADD(month, -6,
                                                                  h.Invoicedate)
                                                  AND     h.Invoicedate
                         )
    FROM    salesdata h
    GROUP BY MONTH(h.Invoicedate) ,
            YEAR(h.Invoicedate)
    ORDER BY YEAR(h.Invoicedate) ,
            MONTH(h.Invoicedate)

| Year      | Month    |    COUNT    |
|-----------|----------|-------------|
|   2014    |    Jan   |           6 |
|   2014    |    Feb   |           6 |
|   2014    |    Mar   |           6 |
|   2014    |    Apr   |           4 |
|   2014    |    May   |           6 |
|   2014    |    Jun   |           6 |

View the table on SQL Fiddle

2 个答案:

答案 0 :(得分:1)

在这里。

WITH dt AS (
-- set invoice to BOM to get one row per month  
SELECT DISTINCT DATEADD(mm,DATEDIFF(mm,0,InvoiceDate),0) AS InvoiceDate
  FROM salesdata
)
SELECT YEAR(dt.InvoiceDate) AS YEAR
     , MONTH(dt.InvoiceDate) AS MONTH
     , COUNT(DISTINCT CustomerId) AS PARTYCOUNT
  FROM salesdata s
 INNER JOIN dt
-- Define your window
    ON s.InvoiceDate >= DATEADD(MM, -2, dt.InvoiceDate)
   AND s.InvoiceDate < DATEADD(MM, 1, dt.InvoiceDate)
 GROUP BY YEAR(dt.InvoiceDate)
     , MONTH(dt.InvoiceDate)
 ORDER BY 1, 2

答案 1 :(得分:0)

您需要将一些聚合函数应用于invoicedate。

这应该有效:fiddle

SELECT 
   -- get the first of the current month and substract two months
   dateadd(month, -2, DATEADD(day, -day(h.Invoicedate) + 1, h.Invoicedate)) as first_of_month,
   PartyCount = ( SELECT   COUNT(DISTINCT s.CustomerID)
                  FROM     salesdata s
                  WHERE    s.Invoicedate >=    dateadd(month, -2, DATEADD(day, -day(h.Invoicedate) + 1, h.Invoicedate))
                    AND    s.Invoicedate < min(dateadd(month,  1, DATEADD(day, -day(h.Invoicedate) + 1, h.Invoicedate)))
                )
FROM    salesdata h
group by
   dateadd(month, -2, DATEADD(day, -day(h.Invoicedate) + 1, h.Invoicedate))
order by 1

我更愿意先创建一个包含月份名称和日期范围的表格,然后再使用它。