Sum total of several MySQL columns stored in another column? - mysql

I have several columns in a MySQL database that I would like to add and store in another column:
column1 column2 column3 subtotal
10 10 10 30
Is there a way to accomplish this?

update yourtable set subtotal = col1 + col2 + col3

If you simply update subtotal, you have to maintain its value - ie every time one of the other columns is updated, your code has to remember to update subtotal too.
There are two ways to address this issue:
Create a trigger that fires when the row is updated. This option requires database "kung fu" and isn't immediately obvious to anyone else looking at the table the the trigger exists
Create a VIEW that does the calculation
I think option 2 is the best approach.
Here's how you code a view.
create view mytable_totalled as
select col1, col2, col3, col1 + col2 + col3 as subtotal
from mytable
Once created, the view can be used just like a table (with a few caveats), but you can certainly do any kind of select on it. The new column is calculated on the fly when selected

How about this?
UPDATE tableName SET subtotal = (column1 + column2 + column3)
Update 1
If you really don't need subtotal column in table just use query as
SELECT *, (column1 + column2 + column3) as subtotal
FROM tableName
Demo

Well if this is just a one time deal you could do an update query like so:
UPDATE MyTable set subtotal = (column1 + column2 + column3)
If you want it to be calculated on insert, you could have a calculated column.
I would personally just wait until you need it to calculate it so that information that could easily be derived from your data isn't bloating your DB.

Related

SQL how to use a formula to fill a column like in Excel

My database is in MySQL
I have a table, let's say of 4 columns.
I would like to know if it's possible, and how to implement the following: fill the 4th column according to the value of the column 2 and column 3
In Excel I have a formula, let's give an example: if column2 value is set to "grey" and column3 value is set to "car", then column 4 value should be set to "super"
I just say this as an example.
My real formula in Excel looks like this: =IF(K4=4;"Maximal";IF(K4>4;"Maximal";IF(K4=3;"Important";IF(K4>3;"Important";IF(K4=2;"Limited";IF(K4>2;"Limited";IF(K4=1;"Forgettable";IF(K4>1;"Forgettable";"error"))))))))
However I want to do it in SQL.
I was thinking of creating my table until the column 3, set column 4 to NULL or empty, then open a GUI written in Java and maybe there do a piece of code to automatically fill the column 4 according to what is in column 2 and column 3 (these values will be choosable via Choicelist).
But if there is a way to do it directly in SQL, I am interested
Thx a lot in advance for your help.
regards
Yes. you can easily update your NULL-values according to some requirements for the other values in other columns of a particular row with the Update statement
UPDATE <tablename>
SET <column> = 'value'
WHERE <condition>
The only drawback here might be that you have to create an update statement for each of the combinations of your values in column2 and column3. (however, it's not much work for your amount of conditions).
I created an example (demo):
Creating a table in SQL according to your example could look like this,I used a temporary one for the sake of an example:
CREATE GLOBAL TEMPORARY TABLE demoTable (
"Col1" VARCHAR2(50 BYTE) NOT NULL,
"Col2" VARCHAR2(50 BYTE) NOT NULL,
"Col3" VARCHAR2(50 BYTE) NOT NULL,
"Col4" VARCHAR2(50 BYTE) DEFAULT NULL
)
ON COMMIT PRESERVE ROWS
I also inserted some dummy data:
INSERT INTO demoTable VALUES ('Charles', 'grey', 'car', NULL);
INSERT INTO demoTable VALUES ('Alice', 'grey', 'bike', NULL);
INSERT INTO demoTable VALUES ('Bob', 'red', 'car', NULL);
The result:
Now, create the update statements like this, for example:
UPDATE demoTable dt
SET dt."Col4" = 'super'
WHERE dt."Col2" = 'grey' AND dt."Col3" = 'car';
The result
You can try like this;
select * from mytable
COL1 COL2
---- --------------------
0 -
1 -
2 -
3 -
4 -
4 record(s) selected.
update mytable Set Col2 =
Case
When Col1<1 Then 'error'
When Col1=1 Then 'Forget'
When Col1=2 Then 'Limited'
When Col1=3 Then 'Important'
When Col1=4 Then 'Maximal'
End"
select * from mytable"
COL1 COL2
---- --------------------
0 Error
1 Forget
2 Limited
3 Important
4 Maximal
4 record(s) selected.
You can create a sql function, lets say udfGetColumn4Value taking in the column2, column3 as parameters to it and return a value.
Now you can run a select column2, column3, udfGetColumn4Value(column2, column3) from table or a query as desired. Hope this helps.
You were not very precise regarding which DBMS you're using. And also about the exact logic behind using your two columns.
Still here comes a probable SQL-Server solution, where I have taken one statement using CASE WHEN with your example and concatenated your two columns col2 and col3 (you can apply your further logic of here) otherwise:
UPDATE TableName
SET Col4 = CASE WHEN col2 = 'red' AND col3 = 'car' THEN 'super' ELSE col2 + col3 END;
You should replace col2 + col3 with your further logic.
Seems that a simple UPDATE-Query could address your problem:
update things set result = "super" where thing = "car" and color = "grey";
The where-clause does what you desire to do by saying
fill the column 4 according to what is in column 2 and column 3
I created a test table here on turorialspoint, there you can check if it fits your needs.

MySql Calculations

I am trying to add columns in MySQL and dynamically populate another columns.
e.g
i have a table 'numbers'
and have column 1, column 2, column 3 and the total of these should be populated in column 4
Unless I'm misunderstanding your question, aren't you just looking for:
UPDATE numbers SET column4 = (column1 + column2 + column3);
That will update column4 in all rows of the table numbers to be the sum of the first 3 columns.
Alternatively, you could also do the addition during SELECT:
SELECT column1, column2, column3, (column1 + column2 + column3) AS column4 FROM numbers;
in which case you wouldn't need an actual column4 in the database table.
Edit:
To make it update column4 every time one of the other columns was updated you could use a trigger: https://dev.mysql.com/doc/refman/5.5/en/trigger-syntax.html (There's actually an example of something very similar in the linked docs.)
Use triggers with caution though, not because there's anything inherently wrong with them — not at all — but because using them sometimes moves logic that belongs in code into a place where it can be difficult to locate, debug and keep in version control.
try
select field_1, field_2, field_3, (field_1+field_2+field_3) as field_4 from your_table

How to add 2 columns in mysql?

I have a table called "attendance" in which there are several columns.
I want to add 2 columns and put the result in the third column in the same table.
How to do it in Mysql?
I want it to happen every time when ever a new entry comes.
UPDATED: If you have no control over INSERT statements and you want your calculated column values to be persisted then you can use a BEFORE INSERT trigger
CREATE TRIGGER tg_bi_attendance
BEFORE INSERT ON attendance
FOR EACH ROW
SET NEW.column3 = NEW.column1 + NEW.column2;
Note: you probably have to cover a case when values in column1 and/or column2 are being updated. Use a separate BEFORE UPDATEtrigger for that.
CREATE TRIGGER tg_bu_attendance
BEFORE UPDATE ON attendance
FOR EACH ROW
SET NEW.column3 = NEW.column1 + NEW.column2;
Here is SQLFiddle demo
Otherwise just calculate it on the fly in SELECT clause
SELECT column1, column2, column1 + column2 column3
FROM attendance
or create a view
CREATE VIEW vw_attendance AS
SELECT column1, column2, column1 + column2 column3
FROM attendance
To update rows that are already in the table use UPDATE
UPDATE attendance
SET column3 = column1 + column2

Update query using select statement of updating table

In Mssql i want to update a column col1 in table named Table1 using select query which returns col1 from Table1 and add 1 to it.
So i used the following code
update Table1 set col1=(select col1 from Table1) + 1;
But when i used it says you cannot target same table.Is there any ways to work out this function.
Please help to find it out.
Thanks in advsnce
you can do it like that
update Table1 set col1= col1 + 1;

Quickest way to duplicate a MySQL Record

Simple question, i have a query with some WHERE and i need to duplicate it with a change to 1 field to a different value? There is a unique increment ID field as well which I cannot duplicate.
Something along these lines should work. This will give you access to the row that you want to duplicate, and you just select the values to insert for the new row, replacing one of them.
INSERT tblData
( -- Lets pretend Column1 is your key
Column2
, Column3
)
SELECT
Column2
, Column3 + 5 /*Replace this with whatever value is you want*/
FROM tblData
WHERE Column1 = #Id
INSERT INTO table(field1,field2)
SELECT field1*x, field2 /*Replace accordingly*/
FROM table
WHERE key = #Id