我正在尝试构建一个Oracle SQL查询,当计数大于1时,它会按行分组以及组成该组的行。请参阅下面的示例和SQL查询分组。任何帮助或建议将不胜感激。
例如,使用以下数据集 -
======================
ID | NAME | AUTHOR
======================
2 | Abc | John
6 | Abc | John
3 | Xyz | Mike
4 | Abc | Mike
5 | Xyz | John
1 | Abc | Mike
7 | PQR | Raj
Expected Result -
===========================
ID | NAME | AUTHOR | COUNT
===========================
| Abc | | 4
2 | Abc | John |
6 | Abc | John |
4 | Abc | Mike |
1 | Abc | Mike |
| PQR | | 1
| Xyz | | 2
3 | Xyz | Mike |
5 | Xyz | John |
SELECT NAME, COUNT(NAME) from (
SELECT 2 as ID, ' Abc ' as NAME, ' John ' as AUTHOR FROM DUAL
UNION
SELECT 6 as ID, ' Abc ' as NAME, ' John ' as AUTHOR FROM DUAL
UNION
SELECT 3 as ID, ' Xyz ' as NAME, ' Mike ' as AUTHOR FROM DUAL
UNION
SELECT 4 as ID, ' Abc ' as NAME, ' Mike ' as AUTHOR FROM DUAL
UNION
SELECT 5 as ID, ' Xyz ' as NAME, ' John ' as AUTHOR FROM DUAL
UNION
SELECT 1 as ID, ' Abc ' as NAME, ' Mike ' as AUTHOR FROM DUAL
UNION
SELECT 7 as ID, ' PQR ' as NAME, ' Raj ' as AUTHOR FROM DUAL)
GROUP BY NAME
ORDER by NAME;
答案 0 :(得分:1)
SQL> with t as (
2 SELECT 2 as ID, ' Abc ' as NAME, ' John ' as AUTHOR FROM DUAL
3 UNION
4 SELECT 6 as ID, ' Abc ' as NAME, ' John ' as AUTHOR FROM DUAL
5 UNION
6 SELECT 3 as ID, ' Xyz ' as NAME, ' Mike ' as AUTHOR FROM DUAL
7 UNION
8 SELECT 4 as ID, ' Abc ' as NAME, ' Mike ' as AUTHOR FROM DUAL
9 UNION
10 SELECT 5 as ID, ' Xyz ' as NAME, ' John ' as AUTHOR FROM DUAL
11 UNION
12 SELECT 1 as ID, ' Abc ' as NAME, ' Mike ' as AUTHOR FROM DUAL
13 UNION
14 SELECT 7 as ID, ' PQR ' as NAME, ' Raj ' as AUTHOR FROM DUAL)
15 select id, name, author, count#
16 from (
17 select t.id, t.name, t.author, decode(grouping(id),1,count(*),null) count#,
18 count(*) over (partition by name) cn, grouping(id) gid
19 from t
20 group by grouping sets((id,name,author),(name))
21 )
22 where (cn != 2 or count# is not null)
23 order by name, gid desc, author
24 /
ID NAME AUTHOR COUNT#
---------- ------ ------ ----------
Abc 4
2 Abc John
6 Abc John
4 Abc Mike
1 Abc Mike
PQR 1
Xyz 2
5 Xyz John
3 Xyz Mike
答案 1 :(得分:0)
select
id, name, author, decode(grouping_id(id, name), 2, count(*)) count
from
books
group by
rollup(name, (author, id))
having
grouping_id(id, name) != 3
order
by name, id nulls first
答案 2 :(得分:0)
按名称分组的数据与作者的数量:
SELECT NULL id, name, NULL author, count(author) "count"
FROM myTable
GROUP BY name
当有多位作者时加上细节:
SELECT id, name, author, NULL "count"
FROM mytable
WHERE name NOT IN (SELECT name FROM myTable GROUP BY name HAVING count(1) = 1)
将这些与一些订单放在一起以获得想要的结果
SELECT id, name, author, NULL "count"
FROM mytable
WHERE name NOT IN (SELECT name FROM myTable GROUP BY name HAVING count(1) = 1)
UNION ALL
SELECT NULL id, name, NULL author, count(author) "count"
FROM myTable
GROUP BY name
ORDER BY 2, 4, 1, 3