SQL 按连续出现的值分组
SQL Grouping by sequential occurrences of a value
我有以下 table 2 列
ID | Dept
1 | A
2 | A
3 | B
4 | B
5 | B
6 | A
我想做一个计数,使输出看起来像下面的 table。
Dept | Count
A | 2
B | 3
A | 1
提前感谢您的帮助!
运行 此查询:
SELECT Dept, count(*) FROM table_name group By Dept
您不能使用 SQL 执行此操作。 Count 计算不同的项目,因此在您的情况下 count 会给您 A
和 B
.
的计数
您只能 count/group 按 table 中的值,不能按行顺序。如果您无论如何都不使用 order by
,则无法保证 SQL 中的顺序。
从您的示例来看,您似乎想要计算每个部门的连续记录。
您可以通过组合行号和订购 ID 来完成此操作。
create table tblDept (
id int not null,
dept varchar(50)
);
insert into tblDept values (1, 'A');
insert into tblDept values (2, 'A');
insert into tblDept values (3, 'B');
insert into tblDept values (4, 'B');
insert into tblDept values (5, 'B');
insert into tblDept values (6, 'A');
with orderedDepts as (
select
dept,
id,
row_number() over (partition by dept order by id) -
row_number() over (order by id) as rn
from tblDept
)
select
dept,
count(*) as num
from orderedDepts
group by
dept,
rn
order by
max(id)
给出输出:
+------+-----+
| DEPT | NUM |
+------+-----+
| A | 2 |
| B | 3 |
| A | 1 |
+------+-----+
与迈克尔的略有不同,结果相同:
with cte1 as (
select id,
dept,
row_number() over (partition by dept order by id) -
row_number() over (order by id) group_num
from test),
cte2 as (
select dept,
group_num,
count(*) c_star,
max(id) max_id
from cte1
group by dept,
group_num)
select dept,
c_star
from cte2
order by max_id;
我有以下 table 2 列
ID | Dept
1 | A
2 | A
3 | B
4 | B
5 | B
6 | A
我想做一个计数,使输出看起来像下面的 table。
Dept | Count
A | 2
B | 3
A | 1
提前感谢您的帮助!
运行 此查询:
SELECT Dept, count(*) FROM table_name group By Dept
您不能使用 SQL 执行此操作。 Count 计算不同的项目,因此在您的情况下 count 会给您 A
和 B
.
您只能 count/group 按 table 中的值,不能按行顺序。如果您无论如何都不使用 order by
,则无法保证 SQL 中的顺序。
从您的示例来看,您似乎想要计算每个部门的连续记录。
您可以通过组合行号和订购 ID 来完成此操作。
create table tblDept (
id int not null,
dept varchar(50)
);
insert into tblDept values (1, 'A');
insert into tblDept values (2, 'A');
insert into tblDept values (3, 'B');
insert into tblDept values (4, 'B');
insert into tblDept values (5, 'B');
insert into tblDept values (6, 'A');
with orderedDepts as (
select
dept,
id,
row_number() over (partition by dept order by id) -
row_number() over (order by id) as rn
from tblDept
)
select
dept,
count(*) as num
from orderedDepts
group by
dept,
rn
order by
max(id)
给出输出:
+------+-----+
| DEPT | NUM |
+------+-----+
| A | 2 |
| B | 3 |
| A | 1 |
+------+-----+
与迈克尔的略有不同,结果相同:
with cte1 as (
select id,
dept,
row_number() over (partition by dept order by id) -
row_number() over (order by id) group_num
from test),
cte2 as (
select dept,
group_num,
count(*) c_star,
max(id) max_id
from cte1
group by dept,
group_num)
select dept,
c_star
from cte2
order by max_id;