将Temp列的结果加入表SQL Server

时间:2015-12-03 10:01:52

标签: sql sql-server

我正在使用SQL Server来创建我的数据库。

我想在我的Table中添加一列来计算每行中NULL值的数量,如下所示:

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

目前,我有这个:

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

我创建了一个名为Score的新列,为了计算它,我使用了:

  |TMP
1 |0
2 |2

返回一个包含我所有行的列和每行的分数:

shuffle

我想使用这些值更新myTable中的分数。

感谢您的帮助。

4 个答案:

答案 0 :(得分:6)

您可以使用计算列 - 一个始终使用给定表达式计算的虚拟列,而不是存储在磁盘上。这样,您可以避免数据一致性问题。语法很简单:

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 
);

要更改现有表并添加此类列,请使用:

 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 

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

答案 1 :(得分:2)

根据其他列存储计算值通常是个坏主意。 (数据冗余,数据不一致的风险。)改为创建视图:

create view MyView as
SELECT column1, column2, column3,
       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

答案 2 :(得分:2)

DECLARE @temp TABLE
(
    Column1 CHAR(1),
    Column2 CHAR(1),
    Column3 CHAR(1),
    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)
)

CREATE VIEW dbo.vw_Table
AS
    SELECT
          t.Column1
        , t.Column2
        , t.Column3
        , Score = (
            SELECT COUNT(t.val)
            FROM (
                VALUES
                    (t.Column1),
                    (t.Column2),
                    (t.Column3)
            ) t(val)
        )
    FROM dbo.test t
GO

ALTER TABLE dbo.tbl
    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) PERSISTED
GO

答案 3 :(得分:2)

UPDATE mt
SET Score = t.Tmp
FROM MyTable mt INNER JOIN (SELECT idx, 
    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 
FROM MyTable) t ON t.idx = mt.idx