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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With