2017-08-30 46 views
0

我開始學習SQL並在下面進行查詢。它提取我需要的數據,但它並沒有拉動最大值benmon,而是顯示所有月份。有什麼建議麼?MAX(Transact-SQL)

select distinct a.casenum+a.type as AG, a.casenum, d.access_number,d.action,d.dateReceived, a.type, b.region, b.admin, b.unit, b.PAS, a.received, a.due, a.timestd, a.dayspend, a.dayspend-a.timestd as BeyondStd, b.imagedate, d.localUse,e.benmon,e.yyyymm 
into #temp131 
FROM AMS.dbo.pendingactions a, AMS.dbo.cases_daily b, AMS.dbo.ags_daily c, sandbox.dbo.workitems17 d, datamart.dbo.fsissue17 e 
where a.item='APPL' and a.casenum=b.casenum and a.casenum+a.type=c.ag and a.casenum=d.casenum and a.casenum=e.casenum 
AND b.admin='88126' and b.region='SC' and d.status <> 'app dis' 
    GO 
update #temp131 set BeyondStd='' where BeyondStd<1 
    GO 
select region, admin,unit,PAS,casenum,access_number,action,max(benmon),yyyymm, type,dateReceived,received, due, timestd, dayspend, beyondstd, imageDate, localuse 
from #temp131 group by region, admin,unit,PAS,casenum,access_number,action,benmon,yyyymm, type,dateReceived,received, due, timestd, dayspend, beyondstd, imageDate, localuse 
+2

什麼是您的RDBMS?請將其添加爲標籤。 – cddt

+3

也請格式化您的問題中的代碼 - 現在很難閱讀。 – cddt

回答

0

從GROUP BY子句中刪除benmon

通常,您在GROUP BY中不需要應用聚合到(MIN,MAX,COUNT,SUM等)的任何列。

+0

它仍然拉#所有月份#。我很感激幫助,明天我找出答案。謝謝 –

+0

在這種情況下,必須有一個附加字段,該字段具有該案例號的多個值。您可以從SELECT和GROUP BY中刪除這些字段,或者以某種方式對它們進行彙總。或者,如果您想列出每個案例編號的多個記錄,並且只顯示每條記錄的最大值,則可以使用CTE。如果您可以顯示一些樣本數據和期望的輸出,那麼提高我的答案會更容易。 – cddt

0

它顯示每個月,因爲你的group by子句中的所有字段。小組將基本彙總所有字段的所有獨特組合,然後應用聚合。所以在你的羣裏通過:

group by region, admin,unit,PAS,casenum,access_number,action,benmon,yyyymm, type 

你有yyyymm和benmon兩個字段。所以它會爲每個月創建「組」。取決於其他領域的獨特性,這就是團隊的獨特性。