Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Is there a better way to write this query?

$
0
0

Hi All,

I have a table with structure shown in the code below(though table is simplified to make it easier to explain). Basically, this is similar to a transaction table but stores aggregated information(at quarter level). AccountsTotal Expenses and Gross Profit are always empty as they are "derived" values. I am trying to write a select statement to compute the derived values. Total Expenses is the sum of accounts where the ID  = 2,3,4 and Gross profit is Operating Income minus Total Expenses. So the select statement needs to show all accounts(including derived ones) with balances and there is going to be data for more than one year.

Do I have to write 3 select statements using UNION to achieve this? Is there a more efficient way? Truly appreciate your help.

DECLARE @ActBalances TABLE ([ID] [int], [Account] [varchar](150), FYYear VARCHAR(10),  Q1 [float], Q2 [float], Q3 [float], Q4 [float])
INSERT INTO @ActBalances VALUES (1, 'TotalExpenses', NULL, NULL, NULL, NULL, NULL)
INSERT INTO @ActBalances VALUES (2, 'Selling & Marketing', 2012, 1000, 500, 300, 400)
INSERT INTO @ActBalances VALUES (3, 'Research & Development', 2012, 1000, 200,1500,300)
INSERT INTO @ActBalances VALUES (4, 'General & Administrative', 2012, 1000, 200, 1500, 300)
INSERT INTO @ActBalances VALUES (5, 'Operating Income', 2012, 1000, 200, 400, 600)
INSERT INTO @ActBalances VALUES (6, 'Gross Profit',NULL, NULL, NULL, NULL, NULL)
SELECT * FROM @ActBalances



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>