我正在尝试编写一个SQL查询,通过与单个记录进行比较,在每个行的架构中获取具有相等值的列数。
例如:
record1: 1, 0, 1, 0, 0
record2: 0, 0, 0, 0, 1
record3: 0, 0, 1, 0, 0
record1
有两个与record2
相同的属性,遍历整个表格,并按每个记录与record1
有没有办法编写一个可以执行此操作的SQL语句?我只找到了比较每一行的方法,并指定哪些属性必须具有相同的值。
答案 0 :(得分:1)
你可以这样做:
class APIdata( val value: String, private val anotherValue: String) {
fun mapToBoolean(string: String) =
when (string.toLowerCase()) {
"yes" -> true
"on" -> true
else -> false
}
constructor(value: Boolean, anotherValue: Boolean) :
this(if (value) "on" else "off", if (anotherValue) "yes" else "no")
fun getValue(): Boolean {
return mapToBoolean(value)
}
fun getAnotherValue(): Boolean {
return mapToBoolean(anotherValue)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as APIdata
if (getValue() != other.getValue()) return false
if (getAnotherValue() != other.getAnotherValue()) return false
return true
}
override fun hashCode(): Int {
var result = getValue().hashCode()
result = 31 * result + getAnotherValue().hashCode()
return result
}
}
答案 1 :(得分:0)
这是一个很好的例程,您可以在SQL Server中使用,如果您愿意,可以执行此操作。将#temp替换为您的表名:
declare @holding table (id int, col1 int, col2 int, col3 int, col4 int, col5 int, num_in_common int)
declare @iterator int = 1
declare @row1col1 int, @row1col2 int, @row1col3 int, @row1col4 int ,@row1col5 int
while @iterator<=(select max(id) from #temp)
begin
if @iterator=1
select @row1col1=col1, @row1col2=col2, @row1col3=col3, @row1col4=col4 ,@row1col5=col5
from #temp where id=@iterator
else
insert @holding
select *, case when col1-@row1col1 = 0 then 1 else 0 end +
case when col2-@row1col2 = 0 then 1 else 0 end +
case when col3-@row1col3 = 0 then 1 else 0 end +
case when col4-@row1col4 = 0 then 1 else 0 end +
case when col5-@row1col5 = 0 then 1 else 0 end
from #temp where id=@iterator
set @iterator=@iterator+1
end
select * from @holding