I have two columns in a SQL table and I need a third column with the sum of the other two.
It's possible to add a calculated column?
SELECT WRAP_DURATION, IS_SERV_TYP_FLAG,
FROM RVM_DM.FACT_INTERACTION_SEGMENT
Yes it is possible. I did this in the following query, of course, if the columns are numeric
SELECT Col1,Col2,SUM(Col1 + Col2) AS Column3
FROM yourTable
GROUP BY Col1,Col2
If you want to combine two columns, use the following query
SELECT Col1,Col2,CONCAT(Col1,' ', Col2) AS Column3,
FROM yourTable
Example
SELECT Col1,Col2,nvl(Col1,0) + nvl(Col2,0) AS Column3
FROM yourTable
Try this
SELECT WRAP_DURATION, IS_SERV_TYP_FLAG, NVL(WRAP_DURATION,0) + NVL(IS_SERV_TYP_FLAG,0) SUM_OF_TWO_COL
FROM RVM_DM.FACT_INTERACTION_SEGMENT
Oracle supports generated columns, so you can just add this to the table:
ALTER TABLE RVM_DM.FACT_INTERACTION_SEGMENT ADD calculated INT
GENERATED ALWAYS AS (WRAP_DURATION + IS_SERV_TYP_FLAG);
This becomes part of the table definition -- and the value is always correct because it is calculated when it is queried.
I will say that it seems odd to add a flag to a duration, but this works for most expressions that use only columns in one row (or constants).
Oracle offered a virtual column you do with this.
syntax of a virtual column:
column_name [data_type] [GENERATED ALWAYS] AS (expression) [VIRTUAL]
In this syntax:
First, specify the name ( column_name) of the virtual column.
Second, specify the virtual column’s data type. If you omit the data type, the virtual column will take the data type of the result of the expression.
Third, specify an expression in parentheses after the AS keyword. The values of the virtual column will derive from the expression.
1) Creating a table with a virtual column example
create table RVM_DM.FACT_INTERACTION_SEGMENT (
WRAP_DURATION number,
IS_SERV_TYP_FLAG number,
CALC_SUM number generated always as (NVL(WRAP_DURATION,0) + NVL(IS_SERV_TYP_FLAG,0)) virtual
);
2) Adding a virtual column to an existing table example
ALTER TABLE RVM_DM.FACT_INTERACTION_SEGMENT
ADD (
CALC_SUM AS (NVL(WRAP_DURATION,0) + NVL(IS_SERV_TYP_FLAG,0))
);
Related
I have a table with one column and 46 rows and I want to create another column that contains the average of the first column in all 46 rows
e.g.
This is the table:
CREATE TABLE table2
SELECT column1
FROM table1
I want to add another column that contains for each row (46 rows) the value of AVG(column1)
How do can it be done?
You wouldn't use create table to add a column. In this case, a query using a window function is sufficient:
SELECT t1.*, AVG(column1) OVER () as avg_column1
FROM table1 t1;
This is Standard SQL and should work in any database.
I have a table 'zzz' with GpsLatitude and GpsLongitude columns. I want to create a single GPS column (PointWKT) from GpsLatitude and GpsLongitude columns and add it to the existing table 'zzz'.
Query for creating a single column PointWKT:
SELECT
ST_GeogPoint(GpsLongitude, GpsLatitude) AS PointWKT,
FROM
`xxx.yyy.zzz`
I would like to add this query result column PointWKT to an existing table 'zzz'. Correct answer:
SELECT DateTime, SerialNumber, TotalWorkingHours, ...
ST_GeogPoint(GpsLongitude, GpsLatitude) AS PointWKT,
FROM
`login-eko.telematics_latest_K2020.tractor_reports_p` BoundaryWKT
This answer was provided by #Kuki.
You just use ST_GeogPoint(GpsLongitude, GpsLatitude) AS PointWKT
within you select statement, as follows:
SELECT DateTime, SerialNumber, TotalWorkingHours, ...
ST_GeogPoint(GpsLongitude, GpsLatitude) AS PointWKT,
FROM
`project.dataset.table` BoundaryWKT
This question already has answers here:
Can you SELECT everything, but 1 or 2 fields, without writer's cramp?
(12 answers)
Closed 5 years ago.
I am using Oracle Database and I need to realize a query which retrieves all the values of a table record (for a specific WHERE condition), except for one which is known.
Imagine to have the following table:
Sample table
Where you do not want to retrieve the "Age" column, but where - in next releases of the software - the table could have more columns respect to the ones actually present.
Is there any command in Oracle which excludes a specific column (always known, as in the example "Age") and allows me to retrieve all the other values?
Thanks in advance!
You can make that particular column Invisible using following query:
alter table TABLE_NAME modify COLUMN_NAME INVISIBLE;
This will exclude that column from select * statement unless and until you specify that particular column in select clause like below:
select COLUMN_NAME from TABLE_NAME;
From Your sample data:
alter table SAMPLE_TABLE modify Age INVISIBLE;
select * FROM SAMPLE_TABLE will produce
select FirstName, LastName, Address, City, Age from SAMPLE_TABLE will produce:
There are several approaches
1)You can set column UNUSED.It won't be retrieved (and it wont be used) with the queries. This would be permanent. You can't get then column back, the only allowed op would be DROP UNUSED COLUMNS.
ALTER TABLE sample_table SET UNUSED(age);
2)You can set column INVISIBLE, this is temporary. It won't be retrieved, unless you explicitly reference it in SELECT query.
ALTER TABLE sample_table MODIFY age INVISIBLE;
// to change it back to VISIBLE
ALTER TABLE sample_table MODIFY age VISIBLE;
3)Create VIEW without age column and then query view instead of querying TABLE.
CREATE VIEW sample_table_view AS
SELECT first_name, last_name, address, city FROM sample_table;
I would like to be able to add columns to a table with cells who's values are computed by need at 'querytime' when (possibly) selecting over them.
Are there some established ways of doing this?
EDIT: Okay I can do without the 'add columns'. What I want is to make a select query which searches some (if they exist) rows with all needed values computed (some function) and also fills in some of the rows which does not have all needed values computed. So each query would do it's part in extending the data a bit.
(Some columns would start out as null values or similar)
I guess I'll do the extending part first and the query after
You use select expression, especially if you don't plan to store the calculation results, or they are dependant on more than one table. An example, as simple as it could be:
SELECT id, (id+1) as next_id FROM table;
What type of database are you asking for? If it is SQL Server then you can use the computed columns by using the AS syntax.
Eg:
create table Test
(
Id int identity(1,1),
col1 varchar(2) default 'NO',
col2 as col1 + ' - Why?'
)
go
insert into Test
default values
go
select * from Test
drop table Test
In the SQL world it's usually expensive to add a column to an existing table so I'd advise against it. Maybe you can manage with something like this:
SELECT OrderID,
ProductID,
UnitPrice*Quantity AS "Regular Price",
UnitPrice*Quantity-UnitPrice*Quantity*Discount AS "Price After Discount"
FROM order_details;
If you really insist on adding a new column, you could go for something like (not tested):
ALTER TABLE order_details ADD column_name datatype
UPDATE order_details SET column_name = UnitPrice+1
You basically ALTER TABLE to add the new column, then perform an UPDATE operation on all the table to set the value of the newly added column.
I have 2 tables in 2 different databases. The first table (Custumers) Has many data with 10-12 coulmns.
Then I have the Second table(CustumersNew), it has new columns that should represent the same columns as Custumers just with different names and datatypes. CustumersNew is currently empty. I want to move all of the data from table Custumers to table CustumersNew.
The thing here is that table Custumers UserID column has the datatype uniqueidentifier
and the CustumerNew ID column has the datatype int. So as the rest of the coulmns, they sinply do not match in datatypes.
How do i move the data from A to B?
EDIT:
I'm using MS-SQL
I would use the INSERT INTO CustumersNew(<column list>) SELECT <column list from Custumers CONVERTed to data types that match the data type of corresponding columns in CustumersNew> FROM Custumers statement.
E.g.
INSERT INTO CustumersNew(UserId, Name, Age)
SELECT UserId, CONVERT(NVARCHAR(128), Name), CONVERT(INT, Age)
FROM Custumers
I am assuming that Name and Age are of different types in these two tables. You would need to write a similar convert statements where the data type argument should match the data type in the CustumersNew table.
Since UserId/CustomerId being uniqueidentifier cannot be mapped to integer and I doubt the relevance of the values in this column from a functional perspective, I would model the UserId/CustomerId as an AUTO/IDENTITY column in the new table.
Well, you can't store a uniqueidentifier in an int column so you'll have to come up with a new set of keys.
Most database systems provide a mechanism for sequentially numbering records with integer values. In SQL Server, they use IDENTITY columns, in Oracle they use sequences, I think that in MySql you specify the column as auto_increment.
Once you have set up your new table (with it's auto-numbering scheme) then simply insert the data using SQL:
INSERT INTO CUSTOMERS_NEW (COL2, COL3, COL4)
SELECT COL2, COL3, COL4 FROM CUSTOMERS
Notice that the insert statement does not include the ID column - that should be populated automatically for you.
if you are not able to use insert and have to use update it will be like this
UPDATE change
SET widget_id = (SELECT insert_widget.widget_id
FROM insert_widget
WHERE change.id = insert_widget.id)
WHERE change.id = (SELECT insert_widget.id
FROM insert_widget
WHERE change.id = insert_widget.id)
in this example, I wanted to move widget_id column form insert_widget table to change table, but change table already has data, so I have to use update statement