2016-12-13 58 views
0

我有以下幾點。但是在最終的結果中,一些員工ID被計算兩次。我的目標是爲[UniqueEmployees]列僅統計不同employeeID ...有人可以幫我嗎?SQL Server:重複計數

這是這裏的代碼:

IF OBJECT_ID(N'tempdb..#GG') IS NOT NULL 
     DROP TABLE #GG 

SELECT DISTINCT 
    [month], vv.Hiremonth, 
    LoanNumber, vv.EmployeeId, 
    agentname, 
    vv.YearsOfService, vv.MonthsofService, 
    vv.TenureGrouping, vv.TenureMonthGrouping, 
    manager, 
    SUM([Call Counts]) as Calls, 
    SUM(opportunities) as Opportunities, 
    SUM([Discussed w/Customer]) as [Discussed w/Customer], 
    SUM(DidNotDiscuss) as [DidNotDiscuss], 
    SUM(CustomerInterested) as CustomerInterested, 
    (SELECT COUNT(DISTINCT MGR.EmployeeId) 
    FROM #MANAGERS MGR 
    WHERE --EmployeeId = EmployeeId  
      --and 
      CAST(CONVERT(datetime, RIGHT(MGR.HireMonth, 4) + LEFT(MGR.HireMonth, 2) + '01') as DATE) <= CAST(CONVERT(datetime, right([Month], 4) + left([Month], 2) + '01') as DATE) 
      --and MonthsOfService = MonthsOfService 
      --and YearsOfService = YearsOfService 
    ) as UniqueEmployees 
INTO 
    #GG 
FROM 
    #FINALtemp2b VV 
--left join 
    --(select distinct Employeeid 
    --from #FINALtemp2b) CC 
    --on CC.EmployeeId = VV.EmployeeId 
GROUP BY 
    [month], vv.Hiremonth, LoanNumber, vv.EmployeeId, 
    agentname, vv.YearsOfService, vv.MonthsofService, 
    vv.TenureGrouping, vv.TenureMonthGrouping, manager 
ORDER BY 
    [month] 
+0

向我們展示示例數據和預期輸出。 \t請閱讀[**如何提問**](http://stackoverflow.com/help/how-to-ask) \t \t這裏是一個偉大的地方[** START **] (http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)來了解如何提高您的問題質量並獲得更好的答案。 (**)如何創建最小,完整和可驗證的示例**(http://stackoverflow.com/help/mcve) –

+0

「count(distinct ...)」是正確的。也就是說,你正在使用太多我們不知道的臨時表。你能減少你的查詢到一個最小的例子,包括一個輸入來顯示它不起作用嗎? –

+0

你可以在select和group中加入employee_id,然後它會顯示哪些是計數兩次,它可能會給你一些關於爲什麼計數兩次的見解。 – user3700389

回答

0

嘗試取出第一個「獨特」和多餘的「選擇」。

IF OBJECT_ID(N'tempdb..#GG') is not null Drop Table #GG 
select * 
into #GG 
from (
    select 
     [month], 
     vv.Hiremonth, 
     LoanNumber, 
     vv.EmployeeId, 
     agentname, 
     vv.YearsOfService, 
     vv.MonthsofService, 
     vv.TenureGrouping, 
     vv.TenureMonthGrouping, 
     manager, 
     SUM([Call Counts]) as Calls, 
     sum(opportunities) as Opportunities, 
     sum([Discussed w/Customer]) as [Discussed w/Customer], 
     sum(DidNotDiscuss) as [DidNotDiscuss], 
     sum(CustomerInterested) as CustomerInterested, 
     count(distinct (MGR.EmployeeId)) 
    from #MANAGERS MGR 
    where cast(convert(datetime,right(MGR.HireMonth,4) + left(MGR.HireMonth,2) + '01') as DATE) <= cast(convert(datetime,right([Month],4) + left([Month],2) + '01') as DATE) 
    group by 
     [month], 
     vv.Hiremonth, 
     LoanNumber, 
     vv.EmployeeId, 
     agentname, 
     vv.YearsOfService, 
     vv.MonthsofService, 
     vv.TenureGrouping, 
     vv.TenureMonthGrouping, 
     manager 

) as UniqueEmployees 
+0

嗨。我寧願在圖片中保留VV別名表。 – user2811136