简体   繁体   中英

MAX (Transact-SQL)

I'm starting to learn SQL and have the query below. It pulls the data I need but it is not pulling the max benmon , instead it is showing all months. Any suggestions?

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 

Remove benmon from your GROUP BY clause.

Generally, any column you're applying an aggregate to (MIN, MAX, COUNT, SUM, etc.) is not needed in the GROUP BY.

It is showing each month because of all the fields in your group by clause. The group by will basically rollup all of the unique combinations of ALL the fields and then apply the aggregation. So in your group by:

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

you have yyyymm and benmon as two of the fields. So it will create "groups" for each month. Depending on how unique the rest of the fields are that is how unique the group will be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM