Question

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!

Was it helpful?

Solution

GROUP BY and HAVING are the wrong way around in your SQL

OTHER TIPS

GROUP BYshould come before HAVINGlike:

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) 
group by invco, invno
having sum(invtot)<>inv_total_amt;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top