SQL Server:计算在Select中是否匹配两列

时间:2014-04-15 15:56:16

标签: sql sql-server select count

我有一个存储过程,它使用以下行来从表中的两列中获取数据。

有没有办法除了下面我可以比较两列并计算这个百分比?

我正在寻找的是一个数字(以%表示)表示col1和col2中数据匹配的所选记录的数量,例如:说“60%”。

BEGIN
    SET NOCOUNT ON;
    SELECT      col1,
                col2
    FROM        LogTable
    FOR XML PATH('archive'), ELEMENTS, TYPE, ROOT('ranks')
END

非常感谢你提供任何帮助,蒂姆。

1 个答案:

答案 0 :(得分:1)

这可能会包含错误,但尚未对其进行测试。

declare @i int;
set @i = 0;
declare @t table
(
int id identity,
varchar(max) col1,
varchar(max) col2
)

insert into @t(col1,col2)
select col1,
            col2 from  FROM        LogTable
FOR XML PATH('archive'), ELEMENTS, TYPE, ROOT('ranks');

set i = 0;
declare @sum int
set @sum = 0;
while(i < select count(*) from @t)
begin 
 select case when (col1 == col2) then @sum = @sum+1 else @sum from @t
where id = i;
i++;
end

print @sum / select count(*) from @t

或这些行之间的某些内容,没有SQL Management studio来测试atm。