基于字节动态选择列

时间:2016-10-21 09:35:38

标签: sql sql-server tsql

要创建一组商品,我们会比较所有商品,以找到那些具有' Something'共同的。

这个小小的东西'由存储ColumnName和ByteValue的表定义。为了知道我们需要对哪一列进行比较。

正如一张图片经常说的不仅仅是文字,这是一个基本的草图。

表存储ByteField表示的参数:

以绿色和列组合的示例用作比较器,给我们71作为比较器。

Table Parameter that store the ByteField Signification

表格数据 enter image description here

如何构建一个返回Data Id列表的查询,将Data Id作为输入作为比较的基础和Column的预定义组合?这里71

对于此示例,我们假设我们根据DataID = 1和Byte = 71查找Set项。预期结果为:1, 4, 5

这是a sample of the database

因为我曾经被咬过一次",我并没有要求你做我的工作。我正在用一些代码处理它,但我很想知道如何在T-SQL中做到这一点。这就是我提供样本表的原因。

1 个答案:

答案 0 :(得分:2)

表“数据”的列与“参数”列中定义的值不匹配。

使用静态SQL,您必须事先知道列的名称。

declare @compactor  int = 71
        ,@DataID    int = 1

select        *
from
      ( select  t.*
                ,min (case "ID" when @DataID then 'Y' end) over (partition by rnk) as is_requested_row
        from   ( select t.*
                        , rank () over
                            (
                                order by  case when @compactor / power(2,0) % 2 = 1 then "Color" end
                                         ,case when @compactor / power(2,1) % 2 = 1 then "Type" end
                                         ,case when @compactor / power(2,2) % 2 = 1 then "Type2" end
                                         ,case when @compactor / power(2,3) % 2 = 1 then "Name" end
                                         ,case when @compactor / power(2,4) % 2 = 1 then "Sci_name"   end
                                         -- ,case when @compactor / power(2,5) % 2 = 1 then "Alias"     end
                                         ,case when @compactor / power(2,6) % 2 = 1 then "Version"  end
                                         -- ,case when @compactor / power(2,7) % 2 = 1 then "Firmware"  end
                                         -- ,case when @compactor / power(2,8) % 2 = 1 then "Brand"     end
                                         -- ,case when @compactor / power(2,9) % 2 = 1 then "Avaidable" end
                            )   as rnk
                  from   "Data" as t
                ) t
        ) t
where is_requested_row = 'Y'
order by    "ID" ;
相关问题