Store a calculated math equation in a Query? - sql

I am working on this:
I would like to know how to create a new column that holds the amount equal to LocalCurrency multiplied by ExchangeRate for each rows of item.

Use a computed column:
alter table t add newcolumn as (localcurrency * exchangerate);
This adds the column to the table so it is calculated automatically when you retrieve it. The value is automatically set so no update is needed.

You can calculate when required in a query or can create a view to do so and use it wherever required.
CREATE VIEW Purchase_details AS
SELECT *, localcurrencyamount*exchangerate
FROM your_table_name
Select * from Purchase_details

Related

How to create a new column in query then populate with a simple calc X*Y

I have two columns. One is MW and the other is Price. I want to create a sql query that creates a third imaginary column called AwardPrice, and within that it will be one column (MW) * another column (Price). These two columns already exist in the same fact table.
I would recommend a computed column:
alter table t add AwardPrice as (MW * Price);
This value is calculated when you query the table, so the value is always accurate and up-to-date.
How to create a new column in query . . .
I want to create a sql query that creates...
I suppose that you want to do that in a SELECT statement as
SELECT *, MW * Price As AwardPrice
FROM YourTableNameHere;

Copy column with mathematic SQL Server

I'm new to SQL Server. I have column with value of product, now I want to add column value + tax (tax = 10% value) on the same table. Any suggestion how to do this the fastest way or should I insert 1 by 1? Can I just copy value column and add some mathematics ? If I can do that can someone show how it work? Thanks.
If the tax is always the same, you can use a computed column:
alter t add value_plus_tax as (value * 1.1);
This calculates the value whenever you need it. Otherwise, you should add the column explicitly and update it:
alter t add value_plus_tax decimal(10, 2); -- or whatever
update t
set value_plus_tax = value * 1.1;
If your tax rate can change, you can store the rate in a separate table and use a view that joins the two tables to retrieve the data...
CREATE TABLE TaxRate (
[Percent] TINYINT
)
GO
CREATE VIEW ValuesWithTax AS
SELECT *, [Value] * [Percent] / 100 ValueWithTax FROM [Values]
CROSS JOIN TaxRate
If tax rate is not a fix value, you can add a column to save tax rate and a computed column to save total value
ALTER TABLE table1 add tax_rate decimal(19,4) DEFAULT(0.1) WITH VALUES
ALTER TABLE table1 add toatal_value as ([value](1+tax_rate))
Add computed column like (having all calculation).
Ie : Below example i have considered sum of value and tax column you can do any calculation (Make sure the calculation should not throw exception consider boundary condition ) .
ALTER TABLE dbo.tableName ADD RetailValue AS (value+tax );
you can make it persisted computed column too.

MS SQL Computed column

I want to create a column based on COUNT(*) on another table, and when a record is deleted from that table it should decrease the value in this new column and vice versa. So, here is the query:
SELECT COUNT (*) FROM dbo.Korisnik1_FakturaStavka GROUP BY dbo.Korisnik1_FakturaStavka.FakturaID
And it returns this:
And when I try to create a computated column like this:
CREATE TABLE test(
NumberOF as (SELECT COUNT (*) FROM dbo.Korisnik1_FakturaStavka GROUP BY dbo.Korisnik1_FakturaStavka.FakturaID) )
I get the following error:
Subqueries are not allowed in this context. Only scalar expressions are allowed.
Here is the main table that I want to compute from:
How can I resolve this ?
You can define a UDF:
create function dbo.NumberOfFakturaID(#id int) returns int as begin
return (select count(1) from Korisnik1_FakturaStavka where id=#id)
end
and then use it as the computed column:
CREATE TABLE test(FakturaID int, NumberOF as dbo.NumberOfFakturaID(FakturaID))
But putting that sort of calc as a computed column should be used with care.
This is too long for a comment.
You can do this by defining a function to calculate the count and using that function in the computed column definition. However, I don't think this is a good idea for frequently used columns, because you will be doing a lot of counting "behind the scenes".
Alternatives:
Set up a view or materialized view with the additional count column.
Do the count explicitly when you need it.
Set up a trigger to store the count in the first table, whenever rows are inserted/updated/deleted from the second table.

Common methods for doing select with computation by need?

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.

Multiplying two columns of same table and storing result to the third column of same table

I m having a table
SALES(sno,comp_name,quantity,costperunit,totalcost)
After supplying the costperunit values, totalcost need to be calculated as "totalcost=quantity*costperunit".
I want to multiply 'quantity' and 'costperunit' columns and store the result in 'totalcost' column of same table.
I have tried this:
insert into SALES(totalcost) select quantity*costperunit as res from SALES
But It failed!
Somebody please help me in achieving this..
Thanks in Advance
Try updating the table
UPDATE SALES SET totalcost=quantity*costperunit
You need to use update.
UPDATE SALES SET totalcost=quantity*costperunit
It would be better if you do not calculate this field manually but make it a computed column instead - so it calculates automatically for you.
You can change the column with following query:
ALTER TABLE Sales
DROP COLUMN totalcost
ALTER TABLE Sales
ADD totalcost AS quantity*costperunit
DEMO
try this while inserting new row
INSERT INTO test(sno,comp_name,quantity,costperunit,totalcost)
Values (1,#comp_name,#quantity,#costperunit,#quantity*#costperunit)
Best not to store fields that can be calculated, but if you want to, with SQL Server you can set a field to be calculated automatically when values are there.