2014-02-28 30 views
1

我已經搜索過,但沒有找到我的問題的答案。我的問題是,如果我使用下面的查詢,我得到正確的計數是90:與羣組的不同計數

select count(distinct account_id) 
from FactCustomerAccount f 
join DimDate d on f.date_id = d.datekey 

-- 90 

但是當我按CalendarYear下面我錯過了12項。查詢和輸出如下:

select CalendarYear,count(distinct account_id) as accountCount 
from FactCustomerAccount f 
join DimDate d on f.date_id = d.datekey 
group by CalendarYear 

output: 

CalendarYear accountCount 
2005 10 
2006 26 
2007 49 
2008 63 
2009 65 
2010 78 

我不知道爲什麼我失蹤了12次。爲了調試我運行下面的查詢,如果我在FactCustomerAccount失蹤DATE_ID但沒有發現丟失的鑰匙:

select distinct f.date_id from FactCustomerAccount f 
where f.date_id not in 
(select DateKey from dimdate d) 

我使用SQL Server 2008 R2。 任何人都可以請建議什麼可能是失蹤12計數的原因? 在此先感謝。

編輯一個:

我不明白在2個答覆給我的問題原因/答案,所以我想下面使用AdventureWorksDW2008R2加2個查詢沒有計數丟失其中:

select count (distinct EmployeeKey) 
from FactSalesQuota f 
join dimdate d on f.DateKey = d.DateKey 

-- out: 17 

select d.CalendarYear, count (distinct EmployeeKey) as Employecount 
from FactSalesQuota f 
join dimdate d on f.DateKey = d.DateKey 
group by d.CalendarYear 

-- out: 

-- CalendarYear Employecount 
-- 2005   10 
-- 2006   14 
-- 2007   17 
-- 2008   17 

所以請糾正我缺少的東西。

+0

這只是一個案例。在那個DB中,獨特的EmployeeKey在2008年是17,並且是所有不同的員工密鑰的相同數量。 –

+0

Shama:在我的回答中顯示積分 –

回答

1

你沒有失蹤12.可能有些賬戶在最後幾年沒有任何活動。

+0

請參閱編輯一。 –

3

你的查詢有很大的不同:

第一:

select count(distinct account_id) 
from FactCustomerAccount f 
join DimDate d on f.date_id = d.datekey 

返回不同賬戶的計數(在所有年),所以如果你有存在於兩年ACCOUNT_ID,你有1 (count)返回。

第二:

分組由CalendarYear所以如果你有兩個不同的年ACCOUNT_ID,這些信息在兩個不同行去。

select CalendarYear,count(distinct account_id) as accountCount 
from FactCustomerAccount f 
join DimDate d on f.date_id = d.datekey 
group by CalendarYear 

編輯

我試着更好地解釋:

我想爲了夫婦的這組數據:(年,ACCOUNT_ID)

`2008 10` 
`2009 10` 
`2010 10` 
`2010 12` 

如果您運行的兩個上查詢您有:

`2` 

`2008 1` 
`2009 1` 
`2010 2` 

因爲只有在去年(2010年)account_ids 10和12都寫他們的行存在兩種不同的ACCOUNT_ID(10和12)和。

但是,如果你有這樣的數據集:

`2008 10` 
`2009 10` 
`2009 12` 
`2010 12` 

你必須:

首先查詢結果: 2

第二查詢結果: 2008 1 2009 2 2010 1

+0

請參閱編輯一。 –

1

我會說,來分析這個,檢查rows.check壓延column.Is有任何的行數與空在calenderyear。或者嘗試軍銜,我不知道

select *, 
ROW_NUMBER()over(partition by CalendarYear,account_id order by CalendarYear) 
from FactSalesQuota f 
join dimdate d on f.DateKey = d.DateKey