I have just began my trip to database languages and encountered the following problem. I have created a table that look like this
tbl1
Year Account AccValue
2014 Sales 1000
2014 Cost -400
2014 Tax -200
2015 Sales 1200
2015 Cost -900
What I want to do is to create a query that calculates financial indicators like Gross Profit (Sales-Cost), Net profit (Sales-Cost-Tax), Gross Margin ([Sales-Cost]/Sales) year-wise, which means eventually I hope to access to a query like this:
Year FAccount FAccValue
2014 Gross profit 600
2014 Net profit 400
2014 Gross margin 60%
2015 Gross profit 300
2015 Net profit 300
2015 Gross margin 25%
I referred to some rudimentary SQL materials I have at hand, but they just covered how to filter and calculate based on data from different columns, such as how to calculate sales from given columns of price and quantity, so basically the calculation output has an equal number of rows as the input.
In this case, I need to select rows of data for calculation based on particular columns ("Year" and "Account"), and store results with specific columns.
It does occur to me that maybe I should store results in separate queries like "tbl_grossprofit", "tbl_grossmargin" etc. and create another query to summarize them, but I am not sure which one is "conventional" in this case.
Sorry if this is a basic question, help is greatly appreciated!
--EDIT--
I have been trying to figure how to use sub queries in Access but I cannot figure out a way to use them in this case. So a workaround I did is to create separate queries on sales and profit directly from the raw data with GROUP BY
and WHERE
like this:
qry_Sales
Year Sales
2014 1000
2015 1200
qry_Profit
Year Gross Profit
2014 400
2015 300
Then I created another query on gross profit margin by
SELECT qry_Profit.[Gross profit]/qry_Sales.[Sales] AS [Gross margin], qry_Profit.[Year]
FROM qry_Profit,qry_Sales
GROUP BY [Year]
This did end up with my desired outcome, but if I am to follow this idea, it would mean creating tens of queries. I am sure there is a better way. Could you give me some more advice?
Besides, honestly I wish to store the account names (such as "Gross profit", "Net profit") in rows (like shown in the original post) so I can display them easier in Excel. Thank you.
EDIT 2 I combined some great ideas here and this question and eventually came out with a workaround like
SELECT [Year],
(SELECT Sum(AccValue) FROM tbl AS Cal WHERE Cal.[Year]=tbl.[Year] AND Account=Sales) AS Sales,
(SELECT Sum(AccValue) FROM tbl AS Cal WHERE Cal.[Year]=tbl.[Year] AND Account=Cost) AS Cost,
Sales-Cost AS [Gross profit]
[Gross profit]/Sales AS [Gross Margin]
FROM tbl1
GROUP BY [Year]
--The Sum function is unnecessary here, but in the real case Sales data is divided into many rows.
I haven't finished the entire query, but it seems that I have made one big step forward.