2012-11-06 49 views
2

我對此很新,所以原諒如果這已被張貼(我不知道甚至搜索什麼)。使用總和()與多個where子句

我有2個表,會計和用法

AccountID AccountStartDate AccountEndDate 
------------------------------------------- 
1   12/1/2012   12/1/2013 
2   1/1/2013   1/1/2014 


UsageId AccountID EstimatedUsage StartDate EndDate 
------------------------------------------------------ 
1   1   10    1/1  1/31 
2   1   11    2/1  2/29 
3   1   23    3/1  3/31 
4   1   23    4/1  4/30 
5   1   15    5/1  5/31 
6   1   20    6/1  6/30 
7   1   15    7/1  7/31 
8   1   12    8/1  8/31 
9   1   14    9/1  9/30 
10  1   21    10/1  10/31 
11  1   27    11/1  11/30 
12  1   34    12/1  12/31 
13  2   13    1/1  1/31 
14  2   13    2/1  2/29 
15  2   28    3/1  3/31 
16  2   29    4/1  4/30 
17  2   31    5/1  5/31 
18  2   26    6/1  6/30 
19  2   43    7/1  7/31 
20  2   32    8/1  8/31 
21  2   18    9/1  9/30 
22  2   20    10/1  10/31 
23  2   47    11/1  11/30 
24  2   33    12/1  12/31 

我想編寫一個查詢,讓我估計使用情況每月(從現在開始,直到上個月我們所服務的帳戶)的所有帳戶在該月份提供服務。

結果將如下所示:

Month-Year  Total Est Usage 
------------------------------ 
Oct-12   0 (none being served) 
Nov-12   0 (none being served) 
Dec-12   34 (only accountid 1 being served) 
Jan-13   23 (accountid 1 & 2 being served) 
Feb-13   24 (accountid 1 & 2 being served) 
Mar-13   51 (accountid 1 & 2 being served) 
... 
Dec-13   33 (only accountid 2 being served) 
Jan-14   0 (none being served) 
Feb-14   0 (none being served) 

我假設我需要總結,然後做一組,...但真的不知道我怎麼邏輯奠定想這一點。

+0

使用日期應該有幾年? – Laurence

回答

3

修訂答:

我創建了一個月表列MonthID,月與價值觀一樣(201212,12),(201301,1),... 我還重組了使用表有一個月的專欄,而不是開始日期和結束日期,因爲它使思路更清晰。

http://sqlfiddle.com/#!3/f57d84/6的細節

現在的查詢是:

Select 
    m.MonthID, 
    Sum(u.EstimatedUsage) TotalEstimatedUsage 
From 
    Accounts a 
    Inner Join 
    Usage u 
    On a.AccountID = u.AccountID 
    Inner Join 
    Months m 
    On m.MonthID Between 
     Year(a.AccountStartDate) * 100 + Month(a.AccountStartDate) And 
     Year(a.AccountEndDate) * 100 + Month(a.AccountEndDate) And 
     m.Month = u.Month 
Group By 
    m.MonthID 
Order By 
    1 

以前的答案,以供參考當做慣例範圍爲全日期,而不是幾個月。

Select 
    Year(u.StartDate), 
    Month(u.StartDate), 
    Sum(Case When a.AccountStartDate <= u.StartDate And a.AccountEndDate >= u.EndDate Then u.EstimatedUsage Else 0 End) TotalEstimatedUsage 
From 
    Accounts a 
    Inner Join 
    Usage u 
    On a.AccountID = u.AccountID 
Group By 
    Year(u.StartDate), 
    Month(u.StartDate) 
Order By 
    1, 2 
+0

我對開始/結束日期有點困惑。用量表按月估算帳戶使用情況(不分年份)。所以2013年1月的使用量與2014年1月的使用量相同。所以我需要從當前直到最後一個合同結束時返回所有月份,這將比使用表中的月份數多。 – JeffO

+0

@JeffO我已更新以展示您對待您的要求的方式。您通常會以編程方式生成月表。如果需要,您可以使用CTE在飛行中生成它。如果你想支持任何開始日期/結束日期而不是整個月,你需要一個類似的日子表。如果您的帳戶範圍沒有重疊,您還需要進行一些調查以確保答案的連續月份範圍。 – Laurence