我想创建一个简单的查询来计算列中相似值的数量。示例如下:
declare @temo table (sno int identity, dyscode varchar(200), isVerified bit, isCorrect bit, isRejected bit, isDeleted bit)
insert into @temo values('dys',1,1,0,0)
insert into @temo values('dys',1,1,0,0)
insert into @temo values('dys',1,0,1,0)
insert into @temo values('dys',1,0,0,1)
insert into @temo values('dys',1,0,1,0)
insert into @temo values('dys',1,0,0,1)
insert into @temo values('dys',0,0,0,0)
insert into @temo values('dys',1,0,0,1)
预期输出应
'DYS',7,2,3
请分享一些快速有效的解决方案。此操作需要在数百万条记录上运行,因此性能将是一个非常重要的问题。
答案 0 :(得分:3)
你需要转换位列来对它们执行求和功能,因为求和函数不支持位数据类型。
参考链接:https://msdn.microsoft.com/en-IN/library/ms187810.aspx
以下查询将获得所需的结果: -
SELECT dyscode,
sum(cast(isVerified as int)),
sum(cast(isCorrect as int)),
sum(cast(isRejected as int)),
sum(cast(isDeleted as int))
FROM @temo
GROUP BY dyscode
答案 1 :(得分:0)
好像你只是在总结0/1列:
SELECT dyscode,
SUM(isVerified),
SUM(isCorrect),
SUM(isRejected),
SUM(isDeleted)
FROM @temo
GROUP BY dyscode
答案 2 :(得分:0)
Select dyscode,
sum(isVerified),
sum(isCorrect),
sum(isRejected),
sum(isDeleted)
From
@temo
Group by dyscode
使用sum函数,因为值是二进制的。
答案 3 :(得分:0)
您必须对dyscode列和其他列的总和进行分组。
您可以使用以下查询。
Select dyscode ,SUM(isVerified),SUM(isCorrect),SUM(isRejected),SUM(isDeleted) from #temo group by dyscode