2011-01-13 2 views
2

다음 예제 테이블을 참조하십시오. 나는 각 줄에 1을 세고 싶다. 첫 번째 행의 경우 N_1은 3, 두 번째는 2, 그 다음은 1, 그 다음은 0이어야합니다. 결국 테이블, 열, 값 매개 변수가있는 저장 프로 시저에이를 통합하려고합니다. 실수가 쿼리 bilnil에 있습니다SQL 한 행 내에서 값의 발생을 계산하는 쿼리

CREATE TABLE Have 
(Col1 INT NOT NULL 
, Col2 INT NOT NULL 
, Col3 INT NOT NULL 
, N_1 INT NULL 
) 
INSERT Have (Col1, Col2, Col3) 
    VALUES 
    (1, 1, 1) 
    ,(1, 1, 2) 
    ,(1, 2, 2) 
    ,(2, 2, 2) 
+1

그것은 일반적으로 여러 열에서 동일한 데이터 "종류"를 찾는 경우 데이터 모델이 잘못 징조입니다. –

답변

5

select Col1, Col2, Col3, 
case when col1 = 1 then 1 else 0 end + 
case when col2 = 1 then 1 else 0 end + 
case when col3 = 1 then 1 else 0 end as N_1 
from Have 

시도하거나 당신이 테이블 다음

update Have set N_1 = case when col1 = 1 then 1 else 0 end + 
case when col2 = 1 then 1 else 0 end + 
case when col3 = 1 then 1 else 0 end 

를 업데이트해야하는 경우가

select * from Have 
+0

Dang, just beat me –

+1

AlexDPC에 대한 제안은 'N_1' 열을 계산 열로 작성하는 것입니다. –

+0

감사합니다. 이것이 내가 목표로 한 것입니다. 계산 된 열은 대안이 아닙니다. 계산에 포함 할 열이나 값이 고정되어 있지 않기 때문입니다. – AlexDPC

0

을 수행 할 수 있습니다 ,

이어야합니다.
select *, 
(case Col1 when 1 then 1 else 0 end) + 
(case Col2 when 1 then 1 else 0 end) + 
(case Col3 when 1 then 1 else 0 end) 
from have 
+0

N_1을 채우는 대신 추가 열을 계산합니다. – AlexDPC

1

이 일반 절차는 귀하가 수행하는 작업입니까?

CREATE proc p_count 
@table sysname, @columns nvarchar(max), @value nvarchar(max), @separator char(1) = ',' 
-- expected format of @columns is comma separated names 
-- embedded commas supported by using a different @separator 
as 
declare @sql nvarchar(max) 
set @sql = 
'select *, 
case when ' + replace(@columns, @separator, '=' + QuoteName(@value,'''') + 
' then 1 else 0 end + case when ') + '=' + QuoteName(@value,'''') + ' then 1 else 0 end 
from ' + quotename(@table) 
--print @sql 
exec (@sql) 
GO 

사용법 :

exec p_count 'have', 'col1|[col2]|col3', 1, '|' 
exec p_count 'have', 'col1,col2,col3', 1 

이 대체 버전이 선택적 매개 변수를 가지고 개수와 동일한 테이블의 열을 업데이트합니다.

CREATE proc p_count 
@table sysname, @columns nvarchar(max), @value nvarchar(max), @separator char(1) = ',', @updateto sysname = null 
-- expected format of @columns is comma separated names 
-- embedded commas supported by using a different @separator 
as 
declare @sql nvarchar(max) 
set @sql = 
case when @updateto is null then 'select' else 'update x set ' + quotename(@updateto) + '=' end + 
' case when ' + replace(@columns, @separator, '=' + QuoteName(@value,'''') + 
' then 1 else 0 end + case when ') + '=' + QuoteName(@value,'''') + ' then 1 else 0 end 
from ' + quotename(@table) + ' x' 
print @sql 
exec (@sql) 
GO 

사용 (갱신 N_1) :

exec p_count 'have', 'col1,col2,col3', 1, ',', 'N_1' 
select * from have 
+0

좋아 보인다! 감사. – AlexDPC

관련 문제