用于计算一行中某个值的出现次数的SQL查询

用于计算一行中某个值的出现次数的SQL查询,sql,tsql,sql-server-2008,Sql,Tsql,Sql Server 2008,请参见下面的示例表。我想数一数每行的1。对于第一行,N_1必须是3,对于第二行,N_1必须是2,然后是1,然后是0。最后,我想将其合并到一个存储过程中,其中包含参数表、列和值 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。对于第一行,N_1必须是3,对于第二行,N_1必须是2,然后是1,然后是0。最后,我想将其合并到一个存储过程中,其中包含参数表、列和值

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)
试试这个

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

您的查询中有一个错误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

这是你想要的一般程序吗

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):


如果您在多个列中查找相同的“类型”数据,这通常表明您的数据模型是错误的。AlexDPC的建议是将
N_1
列创建为计算列谢谢,这就是我的目标。计算列不是可选的,因为要包含在计算中的列和值都不是固定的。此列计算一个额外的列,而不是填充N_1。
exec p_count 'have', 'col1,col2,col3', 1, ',', 'N_1'
select * from have