Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Syntax for calculated column from subquery results
Message
From
06/08/2008 21:35:48
 
General information
Forum:
Microsoft SQL Server
Category:
Stored procedures, Triggers, UDFs
Miscellaneous
Thread ID:
01337104
Message ID:
01337127
Views:
9
Your approach got me thinking and I came up with a modification of my original proc that seems to give me what I want
SELECT main.*, main.credits- main.debits - main.creditedamt as balance FROM
(	SELECT 
		credits = (SELECT SUM(ac.yamount) 
			FROM account_credits ac
			WHERE ac.cinmates_id = @cinmates_id) ,
		debits = (SELECT sum(ad.yamount) 
			from account_debits ad 
			WHERE ad.cinmates_id=@cinmates_id) ,
		creditedamt = (SELECT sum(ad.ycreditedamt) 
			from account_debits ad 
			WHERE ad.cinmates_id=@cinmates_id )
) main
I will continue to study the CROSS JOIN as I'm sure there is something in there I need to add to my arsenal as well.



>Hi Charles,
>
>You can use derived table to add a calculated column. Try
>
>SELECT *, credits-debits-creditedamt AS balance
>	FROM (
>		SELECT SUM(ac.yamount) AS credits
>			FROM account_credits ac
>		CROSS JOIN (
>				SELECT sum(ad.yamount) AS debits,
>					sum(ad.ycreditedamt) AS creditedamt
>				FROM account_debits ad
>				WHERE ad.cinmates_id=@cinmates_id
>			) dbt
>		WHERE ac.cinmates_id = @cinmates_id)
>	) sm
>

>I feel that it can be improved but nothing else comes to mind at the moment.
>
>>
	SELECT
>>		credits = (SELECT SUM(ac.yamount)
>>			FROM account_credits ac
>>			WHERE ac.cinmates_id = @cinmates_id) ,
>>		debits = (SELECT sum(ad.yamount)
>>			from account_debits ad
>>			WHERE ad.cinmates_id=@cinmates_id) ,
>>		creditedamt = (SELECT sum(ad.ycreditedamt)
>>			from account_debits ad
>>			WHERE ad.cinmates_id=@cinmates_id )
>>
>>
>>In the above stored proc I would like to add a 4th colum which is balance=credits-debits-creditedamt
>>
>>Would also appreciate any insights as to other ways to design this select.
>>


Charles Hankey

Though a good deal is too strange to be believed, nothing is too strange to have happened.
- Thomas Hardy

Half the harm that is done in this world is due to people who want to feel important. They don't mean to do harm-- but the harm does not interest them. Or they do not see it, or they justify it because they are absorbed in the endless struggle to think well of themselves.

-- T. S. Eliot
Democracy is two wolves and a sheep voting on what to have for lunch.
Liberty is a well-armed sheep contesting the vote.
- Ben Franklin

Pardon him, Theodotus. He is a barbarian, and thinks that the customs of his tribe and island are the laws of nature.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform