Rahul
Rahul

Reputation: 2234

newbie SQL Question regarding computed columns

I have a table with columns Q1 and Q2 say. I now want to define a view such that I have three columns in in Q1 Q2 and H1 such that each entry in H1 is the sum of corresponding entries Q1 and Q1

How can I do this as as SQL Query?

Thanks

Upvotes: 2

Views: 130

Answers (8)

gbn
gbn

Reputation: 432210

All good answers, but I'd consider having a computed column on the table if your RDBMS supports it.

Eg For SQL Server

ALTER TABLE Mytable ADD H1 AS Q1 + Q2

Now it's available in all queries on this table (stored proc, triggers etc) and for constraints

Upvotes: 0

Matt Lacey
Matt Lacey

Reputation: 65564

Something like:

CREATE VIEW [MyView]
AS
SELECT     Q1, Q2, Q1 + Q2 AS H1
FROM       MyTable

Upvotes: 0

Craig
Craig

Reputation: 1287

Assuming Q1 and Q2 are numeric types, this should do:

CREATE VIEW SumView
AS
SELECT Q1, Q2, Q1 + Q2 AS H1
FROM MyTable
GO

Upvotes: 1

Nate
Nate

Reputation: 30636

Something like

SELECT Q1, Q2, Q1 + Q2 as H1 FROM Table;

Upvotes: 0

Itay Karo
Itay Karo

Reputation: 18286

SELECT
  Q1, Q2, Q1 + Q2 AS H1
FROM
  table

Upvotes: 2

Jonathan Wood
Jonathan Wood

Reputation: 67193

SELECT Q1, Q2, Q1 + Q2 AS H1 FROM ...

Upvotes: 1

LaGrandMere
LaGrandMere

Reputation: 10359

I wouyld try this :

CREATE VIEW Q1Q2H1 AS
SELECT Q1,Q2,Q1+Q2 as H1
FROM Table

Upvotes: 8

Neil Knight
Neil Knight

Reputation: 48537

CREATE VIEW ComputedColumn AS
SELECT Q1, Q2, Q1 + Q2 AS H1
  FROM myTable

Upvotes: 3

Related Questions