2011-01-13 57 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