Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Another store procedure question

Status
Not open for further replies.

nc297

Programmer
Apr 7, 2010
162
US
I'm back with another one that I'm having problems with...

This is what I need to get out of the database.

Count(cossn) where dib-mvt-typ='r', org_id='r%' or 's%' and dib-mvt-seq-num = max dib-mvt_seq_num for that cossn and dib_mvt_seq_num!=null

I tried putting this query together and getting:

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

Here's my attempt at the query:

Select t.doc, count(t.clmssn) as PendinDDS

from t2dibpend t

where DIB_MVT_TYP='R' and (org_id like 'R%' or org_id like 'S%')

and (dib_mvt_seq_num = max(dib_mvt_seq_num)
and dib_mvt_seq_num is not null)

group by t.doc


What am I doing wrong?
 
This might work:

Code:
Select t.doc, count(t.clmssn) as PendinDDS

from t2dibpend t

where DIB_MVT_TYP='R' and (org_id like 'R%' or org_id like 'S%')

group by t.doc
Having (dib_mvt_seq_num = max(dib_mvt_seq_num)
and dib_mvt_seq_num is not null)

Not tested.

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Thanks gmmastros I will try it in the morning and get back to you.
 
Thanks Gmmastros I got this to work:

Select t.doc, count(t.clmssn) as PendinDDS, dib_mvt_seq_num
from t2dibpend t
where DIB_MVT_TYP='R' and (org_id like 'R%' or org_id like 'S%')
group by t.doc, dib_mvt_seq_num
Having (dib_mvt_seq_num = max(dib_mvt_seq_num)
and dib_mvt_seq_num is not null)
order by doc

I had to add dib_mvt_seq_num to the select and group by.
 
That's cool, but I would encourage you to double and triple check your output. Something doesn't seem right. I don't doubt that the query parses and runs (which only means there is no syntax error), but I suspect the query doesn't return the correct results either.

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
I spent an hour checking and it does return the info that I need.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top