Total Sum of two columns and show in the third Column - sql

I have a Three columns in the SQL table,
I want to show the sum of the total of two columns in the third column. How can I show that using SQL query.
This is my table structure
Id int Unchecked
Col_A int Unchecked
Col_B int Unchecked
Total int Checked

There is no need to store the total in the table, you can simply calculate it as part of your SQL query as follows:
SELECT
Id,
Col_A,
Col_B,
Col_A + Col_B AS Total
FROM tablename

You can use comuted column for this:
CREATE TABLE [dbo].[Test](
[a] [INT] NULL,
[b] [INT] NULL,
[c] AS ([a]+[b])
) ON [PRIMARY]
GO
INSERT INTO dbo.Test
( a, b )
VALUES ( 1, -- a - int
2 -- b - int
)
SELECT * FROM dbo.Test
Results:
a b c
1 2 3

Here is my table where the colums are salary and variable.
Now i need the sum of basic and variable as total.
Here is the query for that-
select basic,variable,(basic+variable) as total from salary

or if you just want to display total:

Try the following -
ALTER TABLE TABLENAME ADD colC AS ColA * ColB

Related

is possible to unpivot a sql server table using headers as a column and values as another column?

I have a table like this:
TableName
dates
ModelName
BaseUnitPerPallet
pallet
Calendar
June
Null
4
1
Country
June
Null
2
6
Product
June
DOWNSTREAM
Null
8
ProductBOM
June
DOWNSTREAM
9
9
and I want a table like this:
Columns
values
TableName
Calendar
TableName
Country
TableName
Product
TableName
ProductBOM
where columns field is the headers of the previous table, and values are the values in an unpivot way.
I have been trying without success the unpivot logic:
SELECT Columns, Values
FROM
(
SELECT TableName, dates, ModelName, BaseUnitPerPallet, pallet
FROM Database
as source_query
)
UNPIVOT
(
Values FOR Columns IN ( TableName, dates, ModelName, BaseUnitPerPallet, pallete)
)
as pivot_results
any advice or guidance would be great.
Additionally, any resource to do this dinamic? and apply the logic without write the column names?
Thanks in advanceĀ”
I'd recommend using APPLY to unpivot your table
Unpivot using APPLY
DROP TABLE IF EXISTS #YourTable
CREATE TABLE #YourTable (
ID INT IDENTITY(1,1) PRIMARY KEY
,TableName VARCHAR(100)
,Dates Varchar(25)
,ModelName VARCHAR(100)
,BaseUnitPerPallet TINYINT
,Pallet TINYINT
)
INSERT INTO #YourTable
VALUES
('Calendar','June',NULL,4,1)
,('Country','June',NULL,2,6)
,('Product','June','DOWNSTREAM',NULL,8)
,('ProductBOM','June','DOWNSTREAM',9,9)
SELECT A.ID,B.*
FROM #YourTable AS A
CROSS APPLY
(VALUES
('TableName',A.TableName)
,('Dates',A.Dates)
,('ModelName',A.ModelName)
,('BaseUnitPerPallet',CAST(A.BaseUnitPerPallet AS Varchar(100)))
,('Pallet',CAST(A.Pallet AS Varchar(100)))
) AS B(ColumnName,Val)
--WHERE B.Val IS NOT NULL /*Optional in case you want to ignore NULLs*/
ORDER BY A.ID,B.ColumnName

Typo in a column name inside a sub-query, but no "Invalid column name" error

I have a table, let's call it A. I want to delete rows with IDs 1 and 2 from that table. For that, I created a table variable #B, containing values 1 and 2 but that column I will name PK.
Now I do this:
DELETE FROM A
WHERE ID IN (
SELECT ID
FROM #B
)
Notice my (deliberate) programming error. In the sub-select, I have used a wrong column name. Accidentally it is the same name used in table A.
This should result in an 'invalid column name' error, right? Except it does not. It executes. Not only that, all data from table A gets deleted. As if there is no more predicate.
I have created a full demo script:
-- What happened to my data???
IF OBJECT_ID('tempdb..#JustATable') IS NOT NULL
DROP TABLE #JustATable
CREATE TABLE #JustATable (
PK INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
ID INT NOT NULL,
NOTE VARCHAR(100) NOT NULL
)
INSERT INTO #JustATable (ID, NOTE)
SELECT database_id, DB_NAME(database_id)
FROM sys.databases;
SELECT NULL [inserted all the rows from sys.databases into the temptable], *
FROM #JustATable;
DECLARE #JustATableVariable TABLE (
PK INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
ID_2 INT NOT NULL,
NOTE VARCHAR(100) NOT NULL
)
INSERT INTO #JustATableVariable (ID_2, NOTE)
SELECT database_id, DB_NAME(database_id)
FROM sys.databases
WHERE database_id = 2;
SELECT NULL [this is my table variable data], *
FROM #JustATableVariable;
DELETE FROM #JustATable
WHERE ID IN (
SELECT ID_2
FROM #JustATableVariable
);
SELECT NULL [I have just removed tempdb from the temptable], *
FROM #JustATable;
DELETE FROM #JustATable
WHERE ID IN (
SELECT ID /* this is the wrong column name but the same name as used in the temptable column */
FROM #JustATableVariable
);
SELECT NULL [wait...where is my data?], *
FROM #JustATable;
Can someone explain to me what is going on here? Has anyone seen this behavior before? Could this be a bug?
In the subquery ... (select id from #b) the column id is not fully qualified. So according to SQL specs, the RDBMS will first see if id column exists in table #b. If it does not, it will search "upwards" until it finds the id column in table a. The query is effectively identical to:
delete from a where id in (select a.id from #b)
Syntactically correct, semantically wrong.

Unique constraint on any combination of two columns

I am trying to implement a unique constraint for a combination of two columns. I am running oracle 11g.
Specifically I have two columns A and B.
I have a row like below
A B
1 2
Then I want the following combinations to fail when inserted
A B
1 2
2 1
Is this possible to achieve with a unique index in Oracle?
Yes, it is possible(for example using generated columns):
CREATE TABLE tab(A INT NOT NULL, B INT NOT NULL);
ALTER TABLE tab ADD c1 AS (LEAST(A,B));
ALTER TABLE tab ADD c2 AS (GREATEST(A,B));
CREATE UNIQUE INDEX UQ_tab ON tab(c1,c2);
You could hide these columns if needed(Oracle 12c):
ALTER TABLE tab MODIFY c1 INVISIBLE;
ALTER TABLE tab MODIFY c2 INVISIBLE;
DBFiddle Demo
EDIT:
Even simpler approach:
CREATE UNIQUE INDEX UQ_tab ON tab(least(A,B), greatest(A,B));
DBFiddle Demo
You can use a UNIQUE INDEX with LEAST, GREATEST and COALESCE functions:
CREATE TABLE table_name (
a INT,
b INT
);
CREATE UNIQUE INDEX table_name__a__b__u ON TABLE_NAME(
COALESCE( LEAST( a, b ), a, b ),
GREATEST( a, b )
);
You need to include COALESCE in case one of the values is NULL.
DBFiddle
INSERT INTO table_name ( a, b ) VALUES ( 1, 2 );
1 rows affected
INSERT INTO table_name ( a, b ) VALUES ( 3, NULL );
1 rows affected
INSERT INTO table_name ( a, b ) VALUES ( 2, 1 );
ORA-00001: unique constraint (SCHEMA_NAME.TABLE_NAME__A__B__U) violated
INSERT INTO table_name ( a, b ) VALUES ( NULL, 3 );
ORA-00001: unique constraint (SCHEMA_NAME.TABLE_NAME__A__B__U) violated

How to generate AUTOMATIC Number in Teradata SQL

I want to generate AUTOMATIC Number to use TD SQL, for example as follows,
CREATE MULTISET TABLE TEST_TABLE
(
AUTO_NUMBER INT,
NAME VARCHAR(10)
)
PRIMARY INDEX (AUTO_NUMBER);
INSERT INTO TEST_TABLE
VALUES('TOM');
INSERT INTO TEST_TABLE
VALUES('JIM');
INSERT INTO TEST_TABLE
VALUES('JAN');
SELECT * FROM TEST_TABLE;
The result above will be ,
1 TOM
2 JIM
3 JAN
Create a column with the below syntax:
SEQ_NUM decimal(10,0) NOT NULL GENERATED ALWAYS AS IDENTITY
(START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 2147483647
NO CYCLE)
Usually there is a column in the table which is unique.
You can use below technique to add a column in your result set if you dont want to add extra column to your table.
select RANK() OVER ( ORDER BY ),T.* SEQ from TABLE T;
It will give you output like:
1 a xx yy
2 b xx yy
3 c xx yy

Adding a Row Number to a Temp Table in Stored Procedure

I need to get one column from one table and put it in a temp table but also add another column to the temp table that would be the row number but I am not sure how to do that.
The basic problem I have is I have a table of communities and a table of sales and I need to go through the sales table and count how many were in each community. Then if a community has more than 5 then to increment a variable that signifies how many models made quota. My thought was to have a temp table that has each community in it alone with a row number and loop through that based on that row number through the sales table to make sure that I check each sale with each community.
Thanks for the input!
You can use IDENTITY on a #temp table.
IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
begin
drop table #TableOne
end
CREATE TABLE #TableOne
(
SurrogateKeyIDENTITY int not null IDENTITY (1,1) ,
NameOf varchar(12)
)
Insert into #TableOne (NameOf)
Select Alpha From
(
Select 'A' as Alpha UNION ALL Select 'Y' as Alpha UNION ALL Select 'B' as Alpha UNION ALL Select 'Z' as Alpha UNION ALL Select 'C' as Alpha
) as derived1
Order by Alpha
select * from #TableOne
IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
begin
drop table #TableOne
end
Output:
SurrogateKeyIDENTITY NameOf
1 A
2 B
3 C
4 Y
5 Z
You can use this :
CREATE TABLE #TableOne
(
SurrogateKeyIDENTITY int IDENTITY (1,1) ,
NameOf varchar(12)
)