简体   繁体   中英

Substituting Nulls

We have the following table (populated from a data extract from a separate table) with 3 fields:

The table's contents ( /original data source contents) are strictly controlled so that, while Null values can be present in either Ax or Ay, they will never be present in both.

Records 1,2 and 3 are identical with respect to the following agreed rule: "Where a Null value is present then the field entry's value shall be taken from the neighbouring non-null Ax/Ay" With this, Records 1,2 and 3 are interpreted as having Ax and Ay values of 1.

Currently, when performing data analysis, all sql constructs must account for the possible presence of Nulls with the net result that the sql complexity/number of conditions to be checked for is increased which also results in an increased risk of introducing a human error. These risks are amplified in the real table which contains many more similar field pairs where similar rules can be applied. Since all analysis is looking only at the table of extract data and not the original/source data...

--> would it be acceptable practice in this case to pre-prepare/modify the extract table via an UPDATE to pad all such encountered Null values with the respective neighbouring field? ...with the aim of achieving simpler to write/read, perhaps more efficient/faster executing sql.

There is no reason to update the table, this is a path I recommend you not to walk at.
The table is meant for storing the data, not processing it.
What you are looking for is a View for displaying the table as it was meant to be seen, including the agreed rules you have for your data.

For example, for the following code (SQL-Server):

 CREATE TABLE MyTable(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Ax] [int] NULL,
    [Ay] [int] NULL
  )



CREATE VIEW MyView
  AS
  SELECT ID,
        CASE 
         WHEN Ax IS NULL THEN Ay
         Else Ax END 
         as Ax,
        CASE 
        WHEN Ay IS NULL THEN Ax
         Else Ay 
         END as Ay
FROM  MyTable       

INSERT INTO MyTable 
VALUES (1,1)
INSERT INTO MyTable 
VALUES(1,NULL)
INSERT INTO MyTable 
VALUES(NULL,1)
INSERT INTO MyTable 
VALUES(1,2)

SELECT * FROM MyTable
SELECT * FROM MyView

I get:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM