2011-07-11 118 views
1

大家好奇,如果有人可以伸出援手,我有這個tsql腳本(如下所示),當前正在返回基於所有者ID的數據,如果記錄是活動的,並且記錄創建日期小於今天的日期。然後我將數據分組在一起。我想實現的是返回每個公司最近的記錄。TSQL分組/選擇幫助

目前我返回的數據是這樣的:

COMPANY A JOE BLOGS NULL 10088 Green NULL NULL 21/07/2007 16:57 Phone Call 
COMPANY B JOE BLOGS NULL 10059 Green NULL NULL 20/07/2007 14:57 Phone Call 
COMPANY B JOE BLOGS NULL 10059 Green NULL NULL 18/07/2006 09:47 E-mail 
COMPANY B JOE BLOGS NULL 10059 Green NULL NULL 19/07/2006 13:19 E-mail 
COMAPANY C JOE BLOGS NULL 10866 Green NULL NULL 17/08/2007 12:57 Phone Call 
COMAPANY C JOE BLOGS NULL 10866 Green NULL NULL 13/08/2007 10:59 E-mail 
COMAPANY C JOE BLOGS NULL 10866 Green NULL NULL 15/08/2007 14:57 E-mail 

這是我想要的數據返回:

COMPANY A JOE BLOGS NULL 10088 Green NULL NULL 21/07/2007 16:57 Phone Call 
COMPANY B JOE BLOGS NULL 10059 Green NULL NULL 20/07/2007 14:57 Phone Call 
COMAPANY C JOE BLOGS NULL 10866 Green NULL NULL 17/08/2007 12:57 Phone Call 

可能有人,指出我在正確的方向嗎?

SELECT fa.name, fa.owneridname, fa.new_technicalaccountmanageridname, fa.new_customerid, fa.new_riskstatusname, 
fa.new_numberofopencases, fa.new_numberofurgentopencases, fap.actualend, fap.activitytypecodename, fap.createdby, fap.createdbyname 
FROM FilteredAccount fa 
INNER JOIN FilteredActivityPointer fap ON fa.accountid = fap.regardingobjectid 
WHERE fa.statecodename = 'Active' 
    AND fap.ownerid = '0F995BDC' 
    AND fap.createdon < getdate() 

GROUP BY fa.name, fa.owneridname, fa.new_technicalaccountmanageridname, fa.new_customerid, fa.new_riskstatusname, 
fa.new_numberofopencases, fa.new_numberofurgentopencases, fap.actualend, fap.activitytypecodename, fap.createdby, fap.createdbyname 

回答

0

正好試試這個

SELECT * FROM (
SELECT fa.name, fa.owneridname, fa.new_technicalaccountmanageridname, fa.new_customerid, fa.new_riskstatusname, 
fa.new_numberofopencases, fa.new_numberofurgentopencases, fap.actualend, fap.activitytypecodename, fap.createdby, fap.createdbyname , 
RN = ROW_NUMBER() OVER (PARTITION BY fa.name ORDER BY fap.createdby DESC) 
FROM FilteredAccount fa 
INNER JOIN FilteredActivityPointer fap ON fa.accountid = fap.regardingobjectid 
WHERE fa.statecodename = 'Active' 
    AND fap.ownerid = '0F995BDC' 
    AND fap.createdon < getdate() 
) a WHERE RN = 1 
+0

沿着那我想我什麼的線。然而,當我試圖運行這個時,我在關鍵字'WHERE'附近得到了一個「錯誤的語法。」。我仔細觀察過,看起來不錯。另外我可以運行內部選擇的罰款,並返回行號! –

+0

找出未來參考的錯誤。需要聲明一個表,我們從中選擇外部選擇!歡呼的幫助和腳本:) –

+0

更正。我的錯。 –