使用分析函数进行分组

时间:2017-07-28 15:28:30

标签: sql oracle

我有一张桌子如下。按ID分组,如果count(item)> 1,如果有重复项,请先取不同,然后应用以下条件。
1)如果count(item)> 1然后,过滤等于65或66的数据。 2)如果count(item)= 1,则什么也不做。

+----+------+
| Id | Item |
+----+------+
|  1 |  65  |
+----+------+
|  1 |  66  |
+----+------+
|  1 |  01  |
+----+------+
|  2 |  93  |
+----+------+
|  3 |  11  |
+----+------+
|  3 |  12  |
+----+------+
|  4 |  23  |
+----+------+
|  4 |  23  |
+----+------+

输出:

+----+------+
| Id | Item |
+----+------+
|  1 |  65  |
+----+------+
|  1 |  66  |
+----+------+
|  2 |  93  |
+----+------+
|  4 |  23  |
+----+------+

到目前为止尝试了这个。

select id, item
from (select table.*, count(1) over (partition by id) as cnt
      from table
     ) tablt
where cnt > 1 and item in (65, 66) or cnt = 1;

3 个答案:

答案 0 :(得分:0)

我认为我正确地解释了你的谓词:

select distinct id, item
from (select x.*,
            count(1) over (partition by id) as cnt,
            count(distinct item) over (partition by id) as cntdist
      from x 
     ) tablt
where cnt > 1 and item in (65, 66) or cntdist = 1;

但这实际上取决于你使用动词"过滤器"当你使用命令式时,什么都不做"。

当我看到动词"过滤器"时,我将其解释为"过滤掉"。但根据你的输出数据,看起来你的意思是“过滤除65和66"之外的所有内容。”

当你写下"什么都不做"时,我可以轻易地将其解释为"不显示行"。但根据输出,看起来你的意思是“什么都不做,以防止行显示在输出"。我在后一条规则中看到的唯一问题是你只显示(4,23)一次。我已经实现了这个功能,但只能根据您显示的输出解释后一个规则。

答案 1 :(得分:0)

请尝试使用以下代码:

with t1 as 
(select id, item, count(1) over (partition by id) as cnt
      from tablet
     ) 
select id, item
from t1
where 
    cnt > 1 
and 
    item in (65, 66)
or 
    cnt = 1
;

对我来说要求不是很清楚,但我确信“with”条款会解决你的目的。

  • ABHI

答案 2 :(得分:0)

你需要把这个条件" cnt> 1和(65,66)"在()如下面

model.tuned <- tune.svm(label~., data = as.data.frame(data.train.dtm), gamma = 10^(-6:-1), cost = 10^(-1:1))
相关问题