2014-07-06 92 views
2

根據過去三個月的銷售額,我需要獲得不同客戶的月度計數。根據過去三個月的銷售數量計算不同的客戶

要通過增加當月的客戶數和最後三月份的客戶增加了計數,如下所示的結果:

  • 在四月月份,不同的客戶數的(APRIL + MARCH +月)
  • 在五月月,不同的客戶(MAY + APRIL + MARCH)的計數
  • 在六月的月份,不同客戶計數(JUNE + MAY + 4月)
  • 七月月,不同的客戶數的(JULY + JUNE + MAY)

這裏是我的嘗試:

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

回答

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 
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 

我寧願創建一個表月份名稱和日期,然後再簡單地用這個代替範圍。

相關問題