2017-08-30 48 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两个字段。所以它会为每个月创建“组”。取决于其他领域的独特性,这就是团队的独特性。