Link to home
Start Free TrialLog in
Avatar of Mittensonmaui
Mittensonmaui

asked on

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
Avatar of chapmandew
chapmandew
Flag of United States of America image

what issue are you having?
ASKER CERTIFIED SOLUTION
Avatar of chapmandew
chapmandew
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mittensonmaui
Mittensonmaui

ASKER

Hmm interesting, I always thought you needed to use having with group by, but it works
>> 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 (?).