0

Can anyone please advise on how to go about writing a SQL query to include the sum for multiple fields across multiple rows by group. I'm using the below query, but it keeps saying that the fields "in the select line are invalid because it is not contained in either an aggregate function or the GROUP BY clause."

    Select ClaimId,InternalICN,BilledAmt, 
           Sum(PayAmt) as TotPayAmt,Sum(COBAmt) as TotCOBAmt,Sum(PrePayAmt) as  
           TotPrePayAmt 
    from CAIDEnc.IntEncTracking.EncounterList
    where BypassFlag = 0 and
     BypassReason = 0
    group by ClaimId, InternalICN

Any advice would be greatly appreciated. Thanks!

2
  • the only field that is problematic is BilledAmt. What should this be? Commented Jul 11, 2013 at 18:45
  • Thanks, Sparky. I realized that BilledAmt should include an aggregate function or it needs to be included in the Group by clause. Commented Jul 11, 2013 at 19:56

3 Answers 3

1

Depending on what you really want, you have two options:

OPTION #1: Remove the BilledAmt from the SELECT

Select ClaimId,InternalICN, 
           Sum(PayAmt) as TotPayAmt,Sum(COBAmt) as TotCOBAmt,Sum(PrePayAmt) as  
           TotPrePayAmt 
    from CAIDEnc.IntEncTracking.EncounterList
    where BypassFlag = 0 and
     BypassReason = 0
    group by ClaimId, InternalICN

or

OPTION #2: Include the BilledAmt in the GROUP BY

Select ClaimId,InternalICN,BilledAmt, 
           Sum(PayAmt) as TotPayAmt,Sum(COBAmt) as TotCOBAmt,Sum(PrePayAmt) as  
           TotPrePayAmt 
    from CAIDEnc.IntEncTracking.EncounterList
    where BypassFlag = 0 and
     BypassReason = 0
    group by ClaimId, InternalICN,BilledAmt
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this worked. So no field can be included in a Select statement like this, unless it is preceeded with an aggregate function, or in the Group By clause?
1

BilledAmt is not in the group by clause. You must put it there, or aggregate it with a sum, average or other function.

Comments

1

BilledAmt is not in a aggregate query. When you use group by you can only select aggregates or any field in the group by clause/

1 Comment

To clarify the reason why you cannot select BilledAmt is because when you group by the aggregates then there may be multiple values of BilledAmt within each group.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.