0

我们如何使用 group by 只考虑列的某个值

例如

如果该列具有类似的值,并且我只想使用 merge_ind = 'Y' 或 null 对记录进行分组,如果是 N,则记录应被视为单独的值

Merge1  Merge2  
A   Y  
A   Y  
A   Y  
B   Y  
B   Y  
B   Y    
C   N  
C   N  
C   N  
D   N  
D   N  
E   null  
E   null  
F   null  
F   null  
null    null  

o/p 应该是

count   Merge1  merge2  
3   A   Y   
3   B   Y  
1   C   N  
1   C   N  
1   C   N  
1   D   N  
1   D   N  
2   E   null  
1   F   null  
1   null    null

我使用联合来实现它,但对性能不太满意。

谢谢阿里
_

4

3 回答 3

3

你可以这样做:

SQL>  with data as (select 'A' Merge1, 'Y' Merge2 from dual union all
  2  select 'A', 'Y' from dual union all
  3  select 'A', 'Y' from dual union all
  4  select 'B', 'Y' from dual union all
  5  select 'B', 'Y' from dual union all
  6  select 'B', 'Y' from dual union all
  7  select 'C', 'N' from dual union all
  8  select 'C', 'N' from dual union all
  9  select 'C', 'N' from dual union all
 10  select 'D', 'N' from dual union all
 11  select 'D', 'N' from dual union all
 12  select 'E', null from dual union all
 13  select 'E', null from dual union all
 14  select 'F', null from dual union all
 15  select 'F', null from dual union all
 16  select null, null from dual)
 17  select merge1, max(merge2), count(*)
 18    from (select merge1, merge2,
 19                 case when merge2 = 'Y' or merge2 is null then merge2 else to_char(rownum) end grp
 20            from data)
 21   group by merge1, grp
 22   order by merge1;

M M   COUNT(*)
- - ----------
A Y          3
B Y          3
C N          1
C N          1
C N          1
D N          1
D N          1
E            2
F            2
             1

测试小提琴:http ://sqlfiddle.com/#!4/b85cc/1

于 2013-02-04T11:44:44.547 回答
1

尝试:

select Merge1, Merge2, count(*)
from table1
group by Merge1, Merge2, case when Merge2 = 'N' then to_char(rownum) else Merge2 end
order by Merge1

这是一个 sqlfiddle 演示

于 2013-02-04T12:09:28.677 回答
1

经过一些相当大的混乱,我有一个可以完成这项工作的查询,尽管我可以发誓这个问题最初被标记为 mysql,不幸的是,这是一个 mysql 唯一的答案:

select count, merge1, merge2
from (
  select count(*) count, merge1, merge2,
  if(merge2 = 'Y' or merge2 is null, 0, n)
  from (
    select merge1, merge2,
    (@n := if(@n is null, 1, @n + 1)) n
    from t
  ) x
  group by 2, 3, 4
) y

不是 Y 的值被视为具有自己的组的单独值。

它通过为每一行分配一个唯一编号来工作,当值不是 Y 时,它们也有选择地按该编号分组,从而为每个非 Y 行创建一个单独的组。

这是一个运行你的 dara 的查询的sqlfiddle 。

于 2013-02-04T11:44:43.187 回答