473,403 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

How to get the SUM() of identical fields in multiple tables

2
Hi

I have three tables that are not related, each of them has a column named "cost".
I am able to get the SUM() for "cost" in each table. How could I get a total sum
of all three columns "cost" together as one result?

Thanks
Sep 11 '07 #1
3 11519
pbmods
5,821 Expert 4TB
Heya, denisa. Welcome to TSDN!

The first solution that comes to mind would be to UNION the three tables as a subquery and find the SUM of that:

Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.         SUM(`cost`)
  3.     FROM
  4.     (
  5.         (
  6.             SELECT
  7.                     `cost`
  8.                 FROM
  9.                     `table1`
  10.         )
  11.         UNION
  12.         (
  13.             SELECT
  14.                     `cost`
  15.                 FROM
  16.                     `table2`
  17.         )
  18.         UNION
  19.         (
  20.             SELECT
  21.                     `cost`
  22.                 FROM
  23.                     `table3`
  24.         )
  25.     )
  26.  
You may get an error about every derived table needing its own alias. Try this, and we'll go from there.

Though if the data in the tables is truly unrelated, I can't imagine the value of being able to sum them... perhaps the database needs a bit of a design tweak.
Sep 11 '07 #2
denisa
2
Thank you for the fast response. I do indeed get a "Every derived table must have its own alias" but with adding "as some_name" after the last FROM clause the message disappears. So again thank you, you saved me another couple of hours searching for the solution (probably not finding it anyhow).

Beginnings are hard when one doesn't get the principles/logic behind some things yet. And that is also the reason that my "database" for sure needs a big bit of a design tweak. Regarding wanting the sum of columns in unrelated tables - I'm using code from a PHP tutorial to list different kind of expenses per month and have a monthly total.

I decided for simplicity in the beginning phase, before knowing how to do it better, to have instead of one, three expenses tables. They contain partially different columns - eg. one is for gasoline with
id, date, title, description1, liter, cost
another one is for other expenses with
id, date, title, chain, description1, description2, cost
the third one similar but again a bit different.

I thought, if I would merge them, many fields would end up with no value and just take space. I just hope by reading further into those thick books I got, soon there will be the knowledge to make a design that makes more sense.
Sep 12 '07 #3
pbmods
5,821 Expert 4TB
Heya, Denisa.

It always starts out so easy. But nobody wants to live in a tiny house, and contractors are SO expensive....

There are several ways you could combine your tables, some more normalized than others.

Ideally, you'd want to split up your data into a few tables:
  • An `expenses` table, with a numeric primary key, and amount and a date.
  • An `expenses_attributes` table with a field name and field value, as well as a reference to the primary key from `expenses`
  • You might also want an `expenses_categories` and `expenses_categories_map` table so that you can keep categorical data separate from 'memo' fields.

An an example, for gasoline, you might have an entry in `expenses`:
[id:102, date:2007-09-11 20:56:45, amount:45.00]

Then in the `expenses_attributes` table:
[id:102, field:quantity, value:12.85]

Then in `expenses_categories_map`:
[id:102, category:5]

And finally in `expenses_categories`:
[id:5, name:gasoline]

It would take some neat-looking joins to view all your data at once (or you could create some views), but then you could more reliably customize and summarize your data without worrying about data duplication or empty space.

If you wanted to get REALLY exciting (and *fun* to maintain), add a `vendors` table and add a reference to the vendor ID in your `expenses` table:
[id:102, date:2007-09-11 20:56:45, amount:45.00, vendor:86]

And in `vendors`:
[id:86, name:QuikTrip]

[EDIT: And don't forget about split transactions! How's that house coming? :) ]
Sep 12 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Geoff Jones | last post by:
Hiya I'm new to SQL so I hope somebody can help me with the following: Suppose I have two tables. How can I find if the two have "identical rows"; in the sense that they are allowed to have...
15
by: U N Me | last post by:
I have a continuous form that lists records from a query. One of the columns is an amount field, In the footer of the form I place a text box that displays the total (sum) of the amount. The...
2
by: Scott Cannon | last post by:
I am trying to query 3 tables all related by Clinet_ID. The Clients table, Monthly_Expenses table and Monthly_Income table. Each client can have 0>M instances of expenses, past due expenses, and...
1
by: Edward | last post by:
I have two tables recording the sales transactions with purchase_id the common key Table 1 (Recording total amounts and customer info) Purchase_Id (Primary Key) Sales_Total (Total sales...
10
by: Rudolf Bargholz | last post by:
Perhaps some kind soul could help me out with an SQL I have been trying all day to get to work, where one colum is just not summing up the way I want it to. I have the following data GRP_SEQ ...
3
by: dk4300 | last post by:
Thank you so much for looking at this! I need code that takes the first table: tblStartingData Date Product Customer ID Revenue 3/1/06 MCF 1 $10.00 6/1/06 MCF 1 $15.00 ...
2
by: rich | last post by:
Hi I'm new to SQL and am having trouble figuring this one out. Any help would be very much appreciated. I have 2 tables 'A_Totals' & 'B_Totals' each table is identical in construction, each...
0
by: dawnyankee via AccessMonster.com | last post by:
I adapted the code below from steve.minnaar (can't thank you enough) for a table that contains data dating back to 2002 and it works excellent for my hours and amount fields, but the table also...
1
by: ArizonaState | last post by:
I have a Stored Proc which outputs the sum of various fields from a table. CODE ... ... COMPUTE SUM(Field1), SUM(Field2), SUM(Field3)... /CODE I am able to execute the SProc and obtain...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.