2011-01-13 53 views
2

請參閱下面的示例表。我想在每一行中計數1。對於第一行N_1必須是3,對於第二個2,然後是1,然後是0.最後,我希望將這個參數與參數Table,Columns,Value結合到一個存儲過程中。用於統計一行內的值的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

它通常是一個跡象,表明你的數據模型是錯的,如果你正在尋找在多個列中的數據相同的「種」。 – 2011-01-13 11:37:49

回答

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

當然,只是打我 – 2011-01-13 11:42:40

+1

AlexDPC的建議是創建`N_1`列作爲計算列 – 2011-01-13 11:43:11

+0

謝謝,這是我的目標。計算列不是一種替代方法,因爲計算中包含的列和值都是固定的。 – AlexDPC 2011-01-13 12:00:52

0

有一個錯誤在您的查詢bilnil ,應該是

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 
1

這是通用的proc你在做什麼?

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