• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 515
  • Last Modified:

SQL Server Group By having issue

I have the following

SELECT     PCNS_Staff_NO, sum(PCNS_STAFF_SR_ALLOCATION_TOTAL_HOURS)/
           IsNull(NullIf(sum(DateDiff(dd,PCNS_STAFF_SR_ALLOCATION_START_DATE,PCNS_STAFF_SR_ALLOCATION_END_DATE))), 0), 1)
FROM         PCNS_STAFF_SR_ALLOCATION
Group by PCNS_Staff_NO, PCNS_STAFF_SR_ALLOCATION.PCNS_STAFF_SR_ALLOCATION_END_DATE
having PCNS_STAFF_SR_ALLOCATION_END_DATE > '2007/01/01'
order by PCNS_STAFF_NO

I want to group by PCNS_Staff_NO only, but the having clause won't allow it because of the END_DATE field
0
Mittensonmaui
Asked:
Mittensonmaui
  • 2
  • 2
2 Solutions
 
chapmandewCommented:
what issue are you having?
0
 
chapmandewCommented:
try this:
SELECT     PCNS_Staff_NO, sum(PCNS_STAFF_SR_ALLOCATION_TOTAL_HOURS)/
           IsNull(NullIf(sum(DateDiff(dd,MAX(PCNS_STAFF_SR_ALLOCATION_START_DATE),MAX(PCNS_STAFF_SR_ALLOCATION_END_DATE)))), 0), 1)
FROM         PCNS_STAFF_SR_ALLOCATION
Group by PCNS_Staff_NO
having MAX(PCNS_STAFF_SR_ALLOCATION_END_DATE) > '2007/01/01'
order by PCNS_STAFF_NO

Open in new window

0
 
Scott PletcherSenior DBACommented:
You need WHERE not HAVING:

SELECT     PCNS_Staff_NO, sum(PCNS_STAFF_SR_ALLOCATION_TOTAL_HOURS)/
           IsNull(NullIf(sum(DateDiff(dd,PCNS_STAFF_SR_ALLOCATION_START_DATE,PCNS_STAFF_SR_ALLOCATION_END_DATE)), 0), 1)
FROM         PCNS_STAFF_SR_ALLOCATION
where PCNS_STAFF_SR_ALLOCATION_END_DATE > '20070101'
Group by PCNS_Staff_NO
order by PCNS_STAFF_NO
0
 
MittensonmauiAuthor Commented:
Hmm interesting, I always thought you needed to use having with group by, but it works
0
 
Scott PletcherSenior DBACommented:
>> I always thought you needed to use having with group by, but it works <<

That depends on what type of check you are doing.  It's possible you might need both WHERE and HAVING, or either alone.

Btw, the two statements above could yield different results: they are *not* equivalent.  They are only the same if every unique PCNS_Staff_NO has either 1) *no* dates after the desired date or 2) *all* dates
after the desired date.  If the dates for the same Staff_NO are mixed, before and after the date, you should see a different result from the two queries.

Frankly I think the first one is not at all logical but I suppose in theory it could be what you want (?).
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now