我们如何仅使用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
我使用联盟实现了它,但对性能不是很满意。
感谢
阿里
答案 0 :(得分: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
答案 1 :(得分: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行创建一个单独的组。
这是一个sqlfiddle,此查询运行您的dara。
答案 2 :(得分: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