2

I'm completely stuck on how to get around this error: Column InvDate or expression in SELECT list not valid.

I'm trying to update this year and last year's summed amount (along with 8 other amounts) using a single SQL update statement:

update CustStats as c set (c.YTDRevenue, c.LastYearRev) =
(select
 case when h.InvDate >= 20170101 then sum(d.InvAmount) else 0 end, 
 case when h.InvDate >= 20160101 and h.InvDate <= 20161231
        then sum(d.InvAmount) else 0 end
from InvHeader as h join InvDetail as d on d.InvNumber=h.InvNumber
where h.Status = 'FINAL' and h.InvDate >= 20160101
 and c.Customer = h.Customer
group by c.Customer)

Is it possible to do this with one statement or do I need one for each field I want to update?

1 Answer 1

2

I would expect your query to work in DB2. You do have an issue with the GROUP BY and lack of aggregation. Perhaps this will suffice:

update CustStats c
    set (c.YTDRevenue, c.LastYearRev) =
        (select sum(case when h.InvDate >= 20170101 then d.InvAmount else 0 end), 
                sum(case when h.InvDate >= 20160101 and h.InvDate <= 20161231
                         then d.InvAmount else 0 end)
         from InvHeader h join
              InvDetail d
              on d.InvNumber = h.InvNumber
         where h.Status = 'FINAL' and h.InvDate >= 20160101 and
               c.Customer = h.Customer
        );
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the quick reply, Gordon. I had actually forgot to put my sums in my example, but they were in my original example. I edited my original comment to reflect that. If I move the sums to before the case statement I get this error: Number of arguments for function SUM not valid.
It just doesn't like the fact that the date isn't part of the grouping, but is instead being used for the selecting in the top part of the SQL clause instead of after the Where statement. I'm thinking there might be a way with the WITH statement or something, but I just can't figure it out. Thanks for your help though!
The date (at least InvDate is only being used as an argument to sum(). There should be no problem with it.
Hi Gordon, yeah, I would have thought it wouldn't matter but I'm still getting that same error: Column InvDate or expression in SELECT list not valid. I'm reduced to putting each field I want to update in it's own SQL statement, which just kills me! Haha
@GordonLinoff can you vote for [db2i] to be a synonym of [db2400]

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.