计算 table 中序列中相同的行数
Count rows in table that are the same in a sequence
我有一个 table 看起来像这样
+----+------------+------+
| ID | Session_ID | Type |
+----+------------+------+
| 1 | 1 | 2 |
| 2 | 1 | 4 |
| 3 | 1 | 2 |
| 4 | 2 | 2 |
| 5 | 2 | 2 |
| 6 | 3 | 2 |
| 7 | 3 | 1 |
+----+------------+------+
我想计算一个序列中 type
的所有出现次数。
输出看起来像这样:
+------------+------+-----+
| Session_ID | Type | cnt |
+------------+------+-----+
| 1 | 2 | 1 |
| 1 | 4 | 1 |
| 1 | 2 | 1 |
| 2 | 2 | 2 |
| 3 | 2 | 1 |
| 3 | 1 | 1 |
+------------+------+-----+
一个简单的group by
喜欢
SELECT session_id, type, COUNT(type)
FROM table
GROUP BY session_id, type
不起作用,因为我只需要对“接触”的行进行分组。
合并 sql-select 是否可行,或者我需要某种编码。存储过程或应用程序端编码?
更新 序列:
如果下一行有相同的type
,则应计算(按ID
排序)。
确定序列 ID
是 session_ID
的键,因为我只想将具有相同 session_ID
的行分组。
所以如果一个会话中有 3 行
- ID 为 1 的行的类型为 1,
- 并且第二行的类型为 1
- 第 3 行的类型为 2
输入:
+----+------------+------+
| ID | Session_ID | Type |
+----+------------+------+
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 1 | 2 |
+----+------------+------+
顺序是第1行到第2行,这三行应该输出
输出:
+------------+------+-------+
| Session_ID | Type | count |
+------------+------+-------+
| 1 | 1 | 2 |
| 3 | 2 | 1 |
+------------+------+-------+
您可以使用 id
和 row_number()
的差异来确定差距,然后执行计数
;with cte as
(
Select *, id - row_number() over (partition by session_id,type order by id) as grp
from table
)
select session_id,type,count(*) as cnt
from cte
group by session_id,type,grp
order by max(id)
我有一个 table 看起来像这样
+----+------------+------+
| ID | Session_ID | Type |
+----+------------+------+
| 1 | 1 | 2 |
| 2 | 1 | 4 |
| 3 | 1 | 2 |
| 4 | 2 | 2 |
| 5 | 2 | 2 |
| 6 | 3 | 2 |
| 7 | 3 | 1 |
+----+------------+------+
我想计算一个序列中 type
的所有出现次数。
输出看起来像这样:
+------------+------+-----+
| Session_ID | Type | cnt |
+------------+------+-----+
| 1 | 2 | 1 |
| 1 | 4 | 1 |
| 1 | 2 | 1 |
| 2 | 2 | 2 |
| 3 | 2 | 1 |
| 3 | 1 | 1 |
+------------+------+-----+
一个简单的group by
喜欢
SELECT session_id, type, COUNT(type)
FROM table
GROUP BY session_id, type
不起作用,因为我只需要对“接触”的行进行分组。
合并 sql-select 是否可行,或者我需要某种编码。存储过程或应用程序端编码?
更新 序列:
如果下一行有相同的type
,则应计算(按ID
排序)。
确定序列 ID
是 session_ID
的键,因为我只想将具有相同 session_ID
的行分组。
所以如果一个会话中有 3 行
- ID 为 1 的行的类型为 1,
- 并且第二行的类型为 1
- 第 3 行的类型为 2
输入:
+----+------------+------+
| ID | Session_ID | Type |
+----+------------+------+
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 1 | 2 |
+----+------------+------+
顺序是第1行到第2行,这三行应该输出
输出:
+------------+------+-------+
| Session_ID | Type | count |
+------------+------+-------+
| 1 | 1 | 2 |
| 3 | 2 | 1 |
+------------+------+-------+
您可以使用 id
和 row_number()
的差异来确定差距,然后执行计数
;with cte as
(
Select *, id - row_number() over (partition by session_id,type order by id) as grp
from table
)
select session_id,type,count(*) as cnt
from cte
group by session_id,type,grp
order by max(id)