Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 once again struck with another query

Author  Topic 

san79
Starting Member

42 Posts

Posted - 2009-07-02 : 04:09:42
sorry for being such sql illiterate ,:-(
i am having two tables one is planning and other is achieved
i want to sum up the amount in planning vs amount in achieved in single query
like this
quote:

SELECT sum(i.Amount), sum(p.AMT_INVOICE)
FROM PJ_TRN_INV_PLAN AS p INNER JOIN
mst_Invoice AS i ON p.INVOICE_NO = i.Inv_No AND p.REV_HD_CODE = i.Revenue_code
WHERE (p.REV_HD_CODE = 'QMS SOUTH') AND (p.MONTH_CODE = 3) AND (p.YEAR_NO = 2009)

but it is returning Cartesian product instead of giving sum of each.
what to do
thanks in advnace

rohitkumar
Constraint Violating Yak Guru

472 Posts

Posted - 2009-07-02 : 08:02:23
query looks fine, try running it after removing aggregate functions if its picking the records it is supposed to pick.
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2009-07-02 : 08:47:52
is there another column you need to join that was missed out ?


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-07-02 : 12:18:00
it may be better to explain what you want with some sample data as we cant see anything wrong with query posted
Go to Top of Page

Ifor
Aged Yak Warrior

700 Posts

Posted - 2009-07-02 : 13:11:01
While difficult to tell without sample data, the OP may have a 1 to many, or many to many, relationship between the tables. This would result in one or both of the aggregates being wrong. (ie Not a cartesian product but more rows than he was expecting.)

SELECT
SUM(D2.ActualInvoiceAmount) AS ActualInvoiceAmount
,SUM(D1.PlanInvoiceAmount) AS PlanInvoiceAmount
FROM
(
SELECT p.Invoice_NO
,P.Rev_HD_code
,SUM(p.AMT_INVOICE) AS PlanInvoiceAmount
FROM PJ_TRN_INV_PLAN p
WHERE p.REV_HD_CODE = 'QMS SOUTH'
AND p.MONTH_CODE = 3
AND p.YEAR_NO = 2009
GROUP BY p.Invoice_NO
,P.Rev_HD_code
) D1
JOIN
(
SELECT i.Inv_No
,i.Revenue_code
,SUM(i.Amount) AS ActualInvoiceAmount
FROM mst_Invoice i
GROUP BY i.Inv_No
,i.Revenue_code
) D2
ON D1.Invoice_NO = D2.i.Inv_No
AND D1.Rev_HD_code = D2.Revenue_code
Go to Top of Page

san79
Starting Member

42 Posts

Posted - 2009-07-03 : 00:39:41
hail to all the responders, particularly Ifor the yak master :-) you just have figured out what i required. it works perfectly, till this date i dont know we can write queries like this, thank you .
where shall i be able to learn these kind of tweaking. is there any specific book for making query differently. :-) thanks to every one once again
Go to Top of Page
   

- Advertisement -