Possible Duplicate:
sql query to sum the data
I have following table structure
TradeId TableName PricingSecurityID Quantity Price
2008 Fireball.dbo.Bond 506 50 100.0000
2009 Fireball.dbo.Bond 506 50 100.2500
2010 Fireball.dbo.Bond 588 50 100.7500
2338 Fireball.dbo.Bond 588 100 102.5000
I need to take a sum of Quantity of matching or we can say group by particular PricingSecurityID
like for PricingSecurityID=506 I should get quantity=100
and for PricingSecurityID=588 I should get quantity=150
How can I write this SQL query?
I did try with simple group by statement
but as i’m also selecting tradeid i’m getting error :
Column ‘TradeId’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Revised question — the TradeID is also needed.
I’m not wholly convinced the query is sensible, but that’s your problem. It can easily be extended to deal with other tables; just add appropriate JOIN clauses.
Please remember to include a table name in the question — it is astonishing how often SQL questions are asked without giving the table a name (so it is not only you who forgets by any means).
Re-updated question
So the originally anonymous table is, apparently,
Fireball.dbo.TradeorFireball..Trade. I’d probably place the 11-way UNION into a view since it is likely to be used in multiple places. However, ignoring that, we can still slip the information into your query:That’s mostly copy and paste — with some reformatting — of your query, with the extra sub-query tucked away in the FROM clause after the Trade table. Were it my query, I’d be using single-letter (or other short mnemonic) aliases for the last two sub-queries too; I just didn’t spend the time working out what were appropriate abbreviations for SecurityTrade and Securities.