KDB:字符串与 table 的比较

KDB: String comparison with a table

我有一个 table bb:

bb:([]key1: 0 1 2 1 7; col1: 1 2 3 4 5; col2: 5 4 3 2 1; col3:("11";"22" ;"33" ;"44"; "55"))

如何对字符串进行关系比较?假设我想获取 col3 小于或等于 "33"

的记录
select from bb where col3 <= "33"

预期结果:

key1    col1    col2    col3
0       1       5       11
1       2       4       22
2       3       3       33

如果你想让col3保持字符串类型,那么就在qsql查询中临时转换一下?

q)select from bb where ("J"$col3) <= 33
key1 col1 col2 col3
-------------------
0    1    5    "11"
1    2    4    "22"
2    3    3    "33"

一种方法是在比较之前评估字符串:

q)bb:([]key1: 0 1 2 1 7; col1: 1 2 3 4 5; col2: 5 4 3 2 1; col3:("11";"22" ;"33" ;"44"; "55"))
q)bb
key1 col1 col2 col3
-------------------
0    1    5    "11"
1    2    4    "22"
2    3    3    "33"
1    4    2    "44"
7    5    1    "55"
q)
q)
q)select from bb where 33>=value each col3
key1 col1 col2 col3
-------------------
0    1    5    "11"
1    2    4    "22"
2    3    3    "33"

在这种情况下,将每个 returns 字符串值设为整数,然后执行比较

如果您正在寻找经典的字符串比较,无论字符串是否为数字,我建议采用下一种方法:

一个。创建行为类似于常见 Java 比较器的方法。其中 returns 0 当字符串相等时,-1 当第一个字符串小于第二个时, 1 当第一个大于第二个时

 .utils.compare: {$[x~y;0;$[x~first asc (x;y);-1;1]]};
 .utils.less: {-1=.utils.compare[x;y]};
 .utils.lessOrEq: {0>=.utils.compare[x;y]};
 .utils.greater: {1=.utils.compare[x;y]};
 .utils.greaterOrEq: {0<=.utils.compare[x;y]};

b。在 where 子句中使用它们

bb:([]key1: 0 1 2 1 7; 
    col1: 1 2 3 4 5; 
    col2: 5 4 3 2 1; 
    col3:("11";"22" ;"33" ;"44"; "55"));
select from bb where .utils.greaterOrEq["33"]'[col3]

c。如下所示,这适用于任意字符串

cc:([]key1: 0 1 2 1 7; 
    col1: 1 2 3 4 5; 
    col2: 5 4 3 2 1; 
    col3:("abc" ;"def" ;"tyu"; "55poi"; "gab"));
select from cc where .utils.greaterOrEq["ffff"]'[col3]

.utils.compare 也可以写成矢量形式,不过,我不确定它是否会更 time/memory 高效

.utils.compareVector: {
    ?[x~'y;0;?[x~'first each asc each(enlist each x),'enlist each y;-1;1]]
 };