Help comparing Sum to Total amt

  • I need a little help. I have an invoice table and and invoice detail table. I pulled the data I care about from the invoice details table to a temp table (for other calculations). I need to find the invoices where the sum of the detail lines do not equal the total cost in the invoice table. Here is my code:

    Create table #inv_det (

    invco varchar(6),

    invno int,

    invtot money,

    invpd int);

    Insert into #inv_det (invco,invno,invtot,invpd)

    Select invd_inv_co, invd_inv_no, invd_total_cost, invd_glpd_no from invdet inner join invoice on

    invd_inv_co=inv_co and invd_inv_no=inv_no where

    inv_dt>=cast('10-01-13 00:00:00' as datetime) and inv_dt<=cast('10-31-13 11:59:59' as datetime);

    Here is my query:

    Select invco,invno from #inv_det inner join invoice on

    invco=inv_co and invno=inv_no where inv_dt>=cast('10-01-13 00:00:00' as datetime)

    and inv_dt<=cast('10-31-13 11:59:59' as datetime)

    having sum(invtot)<>inv_total_amt

    group by invco, invno;

    When I run my query I get "Server: Msg 156, Level 15, State 1, Line 5

    Incorrect syntax near the keyword 'group'."

    I hope I explained my goal well enough. Hopefully someone can point out what I'm missing. I've tried many variations.

    Thanks!

  • Try moving HAVING to after GROUP BY.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • That took care of the issue. Thought I had already tried that. Thanks for your help!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply