Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join the result of a Temp column to a table SQL Server

Tags:

sql

sql-server

I am using SQL Server to create my database.

I want to add a column to my Table which would calculate the number of NULL values in each row, like this:

Column1 | Column2 | Column3 | Score
a       |   B     |   C     |   0
x       |   NULL  |   NULL  |   2

Currently, I have this:

Column1 | Column2 | Column3
a       |   B     |   C     
x       |   NULL  |   NULL  

I have created a new column called Score, and in order to calculate it, I have used:

SELECT
CASE WHEN Column1 IS NULL THEN 1 ELSE 0 END + 
CASE WHEN Column2 IS NULL THEN 1 ELSE 0 END +
CASE WHEN Column3 IS NULL THEN 1 ELSE 0 END 
As TMP
FROM MyTable

That returns a column with all my lines and the Score for each line:

  |TMP
1 |0
2 |2

I would like to update the column Score in myTable with those values.

Thanks for your help.

like image 659
Ayyoub Avatar asked Dec 03 '15 10:12

Ayyoub


People also ask

Can you join temp tables SQL?

As its name indicates, temporary tables are used to store data temporarily and they can perform CRUD (Create, Read, Update, and Delete), join, and some other operations like the persistent database tables.

How do you join two tables based on conditions?

You join two tables by creating a relationship in the WHERE clause between at least one column from one table and at least one column from another. The join creates a temporary composite table where each pair of rows (one from each table) that satisfies the join condition is linked to form a single row.

How do I create a SQL table from query results?

If you would like to create a new table, the first step is to use the CREATE TABLE clause and the name of the new table (in our example: gamer ). Then, use the AS keyword and provide a SELECT statement that selects data for the new table.


1 Answers

You could use a computed column - a virtual column that is always computed with a given expression, and not stored on disk. This way, you avoid problems with data consistency. The syntax is easy:

CREATE TABLE myTab
(
    column1 datatype
  , column2 datatype
...
  , Score AS CASE WHEN Column1 IS NULL THEN 1 ELSE 0 END +
       CASE WHEN Column2 IS NULL THEN 1 ELSE 0 END +
       CASE WHEN Column3 IS NULL THEN 1 ELSE 0 END 
);

In order to alter the existing table and add such a column, use:

 ALTER TABLE myTab ADD Score AS CASE WHEN Column1 IS NULL THEN 1 ELSE 0 END +
       CASE WHEN Column2 IS NULL THEN 1 ELSE 0 END +
       CASE WHEN Column3 IS NULL THEN 1 ELSE 0 END 

Source: https://msdn.microsoft.com/en-us/library/ms188300.aspx

like image 125
marmarta Avatar answered Sep 24 '22 12:09

marmarta