2011-01-13 20 views
2

次の表の例を参照してください。私は各列の1を数えたいと思います。最初の行では、N_1は2番目の2の場合は1、0の場合は3でなければなりません。最後に、これをテーブル、列、値のパラメータを持つストアドプロシージャに組み込みたいと思います。間違いがあなたのクエリbilnilにありSQL 1行内の値の出現をカウントするクエリ

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

ダング、ちょうど私を打つ –

+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

関連する問題