CREATE TABLE dbo.tatable
(
id numeric(18, 0) NOT NULL,
col1 varchar(2) NOT NULL CHECK ((len(col1) = 1 and col1 between '1' and '7') or col1 = 'NC'),
col2 varchar(2) NOT NULL CHECK ((len(col2) = 1 and col2 between '1' and '7') or col2 = 'NC'),
col3 varchar(2) NOT NULL CHECK ((len(col3) = 1 and col3 between '1' and '7') or col3 = 'NC'),
col4 varchar(2) NOT NULL CHECK ((len(col4) = 1 and col4 between '1' and '7') or col4 = 'NC'),
col5 varchar(2) NOT NULL CHECK ((len(col5) = 1 and col5 between '1' and '7') or col5 = 'NC'),
col6 varchar(2) NOT NULL CHECK ((len(col6) = 1 and col6 between '1' and '7') or col6 = 'NC'),
col7 varchar(2) NOT NULL CHECK ((len(col7) = 1 and col7 between '1' and '7') or col7 = 'NC')
) ON [PRIMARY]
GO
ALTER TABLE dbo.tatable ADD CONSTRAINT
PK_tatable PRIMARY KEY CLUSTERED (
id
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
insert into tatable (id, col1, col2, col3, col4, col5, col6, col7) values (1, '5', '5', '5', '5', '5', '5', '5');
insert into tatable (id, col1, col2, col3, col4, col5, col6, col7) values (2, '1', '2', '3', '4', '5', '6', '7');
insert into tatable (id, col1, col2, col3, col4, col5, col6, col7) values (3, '3', '3', '3', 'NC', '5', '5', '5');
insert into tatable (id, col1, col2, col3, col4, col5, col6, col7) values (4, 'NC', 'NC', 'NC', 'NC', 'NC', 'NC', 'NC');
go
create view tavue as select id, 1 col, case col1 when 'NC' then null else cast(col1 as numeric) end val from tatable
union all select id, 2 col, case col2 when 'NC' then null else cast(col2 as numeric) end val from tatable union all select id, 3 col, case col3 when 'NC' then null else cast(col3 as numeric) end val from tatable
union all select id, 4 col, case col4 when 'NC' then null else cast(col4 as numeric) end val from tatable
union all select id, 5 col, case col5 when 'NC' then null else cast(col5 as numeric) end val from tatable
union all select id, 6 col, case col6 when 'NC' then null else cast(col6 as numeric) end val from tatable
union all select id, 7 col, case col7 when 'NC' then null else cast(col7 as numeric) end val from tatable;
go
select id, avg(val) moy from tavue group by id;
go
|