SQL Query用于计算一行中值的出现次数

时间:2011-01-13 11:22:48

标签: sql tsql sql-server-2008

请参阅以下示例表。我想计算每一行的1。对于第一行,N_1必须是3,对于第二行,然后是1,然后是0.最后,我想将其合并到具有参数Table,Columns,Value的存储过程中。

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)

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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