根据阈值依赖多列的SQL顺序

时间:2015-07-20 14:56:01

标签: sql hana

我正在使用SAP HANA,因此有一些SQL语言无法使用(cte table,一些关键字......)。 我使用的查询给出了与两个分数相关的结果,行根据第一个分数列排序,然后排序到第二个分数列。 我有很多行,第一个得分差别很小,第二个得分差异很大,所以我想根据第二个得分订购查询, 但只有当行和下一行之间的差异不超过阈值时。 得分2可以为空。

现在,我的代码看起来像这样:

select 
      "name",
      "score1",
      "score2",
      LEAD("score1", 1) over (order by "score1" desc, "score2" desc) as "nextscore1"
from
      //myrequest generating results
group by
      "name",
      "score1",
      "score2"
order by 
      case when ("nextscore1" IS NOT NULL) AND ("score1" - "nextscore1" < 0,1) then "score2" else "score1" END DESC,
      case when ("nextscore1" IS NOT NULL) AND ("score1" - "nextscore1" < 0,1) then "score1" else "score2" END DESC

它总是输出我的结果,按照一个然后另一个列排序,但不是我期望的混合排序。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

不确定你在哪里出错了,但对我而言这很有效:

创建列表分数(名称varchar(10),得分1小数(10,4),得分2小数(10,4))

insert into scores values ('v1', 1, NULL);
insert into scores values ('v2', 1.5, 2.2);
insert into scores values ('v3', 1.51, 2.4);
insert into scores values ('v4', 1.6, 2.1);
insert into scores values ('v5', 1.4, 2.78);
insert into scores values ('v6', -1.2, -2.1);
insert into scores values ('v7', -1.1, 2.1);
insert into scores values ('v8', 1, 2);


select name, score1, score2, nextscore1,
      case 
           when ((nextscore1 IS NOT NULL) AND (score1 - nextscore1 < 0.1))
           then score2 
           else score1 
      end score_sort1,
      case when (nextscore1 IS NOT NULL) AND (score1 - nextscore1 < 0.1) 
           then score1 
           else score2 
      end score_sort2
from
    (select 
          name,
          score1,
          score2,
          LEAD(score1, 1) over (order by score1 desc, score2 desc) as     nextscore1
    from
        scores
    group by
          name,
          score1,
          score2)
ORDER BY 
      case 
           when ((nextscore1 IS NOT NULL) AND (score1 - nextscore1 < 0.1))
           then score2 
           else score1 
      end ,  
      case when (nextscore1 IS NOT NULL) AND (score1 - nextscore1 < 0.1) 
           then score1 
           else score2 
      end ;

为了说明我将案例表达也放入选择列表中。

NAME    SCORE1  SCORE2  NEXTSCORE1  SCORE_SORT1 SCORE_SORT2
v6      -1.2000 -2.1000 ?           -1.2000     -2.1000    
v7      -1.1000 2.1000  -1.2000     -1.1000     2.1000     
v1      1.0000  ?       -1.1000     1.0000      ?          
v5      1.4000  2.7800  1.0000      1.4000      2.7800     
v2      1.5000  2.2000  1.4000      1.5000      2.2000     
v8      1.0000  2.0000  1.0000      2.0000      1.0000     << small diff of score1 and nextscore1 => score2 is used for SCORE_SORT1
v4      1.6000  2.1000  1.5100      2.1000      1.6000     << small diff of score1 and nextscore1 => score2 is used for SCORE_SORT1 
v3      1.5100  2.4000  1.5000      2.4000      1.5100     << small diff of score1 and nextscore1 => score2 is used for SCORE_SORT1