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)
 Sub-Select with Calculation

Author  Topic 

oahu9872
Posting Yak Master

112 Posts

Posted - 2009-02-11 : 12:25:30
I am trying to pull information on customers, then join to an invoice table and get the sum of their 2 most recent bills.

Something like this:
select ID, Name, sum(select 2 most recent bills)

This is what I have so far...

SELECT

-- Member Information
e.Rid, e.LastName, e.FirstName,

-- Invoice Information
(I need the sum of these two fields in the 2 most recent recrods from this table, chargeable_invoice)
c.current_premium, c.past_due_amount,

-- Determine if their Amount Due Exceeds 2X the Premium
(c.past_due_amount-(2*c.current_premium)) As Due

-- Join Member and Invoice Table
FROM employee e inner join chargeable_invoice c on e.account = c.account_id

-- Pull Valid Terminated Members
WHERE e.enrollment is Null and e.Rid is not null


GROUP BY e.Rid, e.LastName, e.FirstName, c.current_premium, c.past_due_amount


ORDER BY e.LastName, e.FirstName

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2009-02-11 : 14:25:53
I haven't tested this, so caveat emptor, but the rank function is the way to go

Jim



SELECT

-- Member Information
e.Rid, e.LastName, e.FirstName,

-- Invoice Information
--(I need the sum of these two fields in the 2 most recent recrods from this table, chargeable_invoice)
SUM(c.current_premium)
,SUM( c.past_due_amount)

-- Determine if their Amount Due Exceeds 2X the Premium
(c.past_due_amount-(2*c.current_premium)) As Due

-- Join Member and Invoice Table
FROM
employee e
inner join
(select c.accountid,c.current_premium , c.past_due_amount
,[Rank] = RANK() OVER (PARTITION BY accountid order by yourDateColumn desc)
from chargeable_invoice c
) c


on e.account = c.account_id

-- Pull Valid Terminated Members
WHERE e.enrollment is Null and e.Rid is not null
and c.Rank < 3


GROUP BY e.Rid, e.LastName, e.FirstName, c.current_premium--, c.past_due_amount
Go to Top of Page
   

- Advertisement -