Here’s the question :
I have 2 tables , one containing the base data and one containing data related to the base data with only one value so :
TABLE1
pKey | category1 | category2 | ..3 |etc
TABLE2
pKey | value1 |
Where pKey is unique to each real-world object, a serial number for example.
now, how would I compare the tables to match the values with the objects in the other table with the aim of adding the values of the objects to the “owner” of the objects ?
SCENARIO :
Obj1 is one of many franchises that one guy owns, at the end of the month we get a report stating the expenses/sales etc for all the franchises and all the owners of thereof of the brand and have to calculate how this particular owner did . So we compare the table2 to table1,to get the owner and add up the “nett profit” for this particular franchise to his running total at the end of the day hoping for data that looks like :
Table3
owner | Total Earnings |
I’ve written a query that does the compare :
SELECT * FROM Table1 INNER JOIN Table2 WHERE Table1.pkey = Table2.pKey
The only problem is that that, in itself, isn’t very useful. So is the following process the way of doing this, disregarding syntax errors and me forgetting to press shift all the time :
SELECT DISTINCT(Owner) FROM TABLE1
then loop through Table1 for each owner to get all his pKeys
SELECT pKey FROM Table1 Where Owner = ownerResult.Owner
then compare the results from that to TABLE2 to get the Values
SELECT Value FROM TABLE2 INNER JOIN TABLE1 WHERE table2.pKey = table1.pKey
then do the additions on that result.
Also, does SQL handle floating point numbers, if so are there any special steps I should be taking?
You can do this all in one statement:
What we’re using here are called “aggregate functions.” In this case, it’s
sum, but it could bemaxorminoravgor whatever. Furthermore, we can partition this by using thegroup bystatement, to say, “I only want the aggregates to work at each distinct level of these columns.” In this case,owner.And to answer your last question, yes, it does.
double,decimal, andnumericare all data types that can handle decimal numbers (there are quite a few more, too), but I need to know your type of database server (e.g.-MySQL, SQL Server, Oracle) to answer it more completely. Some even contain amoneyorcurrencydata type, which ensures you don’t have partial cents and what have you.