请教 V 友一个 SQL 问题

2019-08-08 21:21:45 +08:00
 orangeChu
有如下数据:

| id | phoneNum | callType | created |
| --- | ----------- | -------- | ---------------- |
| 1 | 15000000000 | 1 | 2019-08-08 01:02 |
| 2 | 15000000000 | 1 | 2019-08-08 02:03 |
| 3 | 15000000000 | 2 | 2019-08-08 04:05 |
| 4 | 15000000000 | 1 | 2019-08-08 06:07 |

处理成:

| phoneNum | callType | created |
| -------------- | -------- | ---------------- |
| 15000000000 | 1 | 2019-08-08 06:07 |
| 15000000000 | 2 | 2019-08-08 04:05 |
| 15000000000(2) | 1 | 2019-08-08 02:03 |

---

将数据读出来后处理,遍历后处理成想要的数据没啥问题。
但想试试用`SQL`来处理,没成功。
想请教一下 V 友有啥好的思路吗?

---
用的是`sqlite`,有`sqlite`语法最好 :)。先谢过~
3950 次点击
所在节点    MySQL
4 条回复
orangeChu
2019-08-08 21:23:56 +08:00
为啥`md`的`table`语法没生效?
Iamnotfish
2019-08-08 22:27:20 +08:00
'''sqlite

select group_concat(phoneNum), callType, created from table group by callType

'''
抛砖引玉一下,看看大佬怎么回答。PS : V2 的 MD 语法不支持 TABLE
orangeChu
2019-08-08 23:27:01 +08:00
@Iamnotfish 感谢回复,(我还没试您给的答案,将在明天尝试一下)最后自己搞定了。
分享一下结果。(可能没有在描述中说明场景不是那么好搞,场景是这样的,记录来电记录,每次来电插入记录到数据库。展示数据时,按倒序来显示。上下两条号码相同时,根据 callType 来决定是否展示新的一行数据;不同号码时,直接展示该数据。展示结果类似手机上的通话记录~)
```
select phonenum, count(*) as cnt, type, max(created)
from (select t.*,
row_number() over (partition by phonenum order by id) as seqnum,
row_number() over (partition by phonenum, type order by id) as seqnum_t
from t
) t
group by phonenum, type, (seqnum - seqnum_t);
```
orangeChu
2019-08-09 10:11:12 +08:00
@Iamnotfish 尝试了一下,得到的结果好像不是我想要的。
---
补充一下原来的题目:
data
| id | phoneNum | callType | created |
| --- | ----------- | -------- | ---------------- |
| 1 | 15000000000 | 1 | 2019-08-07 01:02 |
| 2 | 15000000000 | 1 | 2019-08-07 02:03 |
| 3 | 15000000000 | 2 | 2019-08-07 04:05 |
| 4 | 15000000000 | 1 | 2019-08-07 05:07 |
| 5 | 15000000000 | 2 | 2019-08-07 06:07 |
| 6 | 15000000000 | 1 | 2019-08-07 06:20 |
| 7 | 15000000000 | 1 | 2019-08-07 06:30 |
| 8 | 15000000001 | 1 | 2019-08-07 07:07 |
| 9 | 15000000000 | 1 | 2019-08-07 08:07 |
| 10 | 15000000000 | 1 | 2019-08-08 08:07 |

result
| phoneNum | callType | created | count |
| -------------- | -------- | ---------------- | ----- |
| 15000000000 | 1 | 2019-08-07 02:03 | 2 |
| 15000000000 | 2 | 2019-08-07 04:05 | 1 |
| 15000000000 | 1 | 2019-08-07 05:07 | 1 |
| 15000000000 | 2 | 2019-08-07 06:07 | 1 |
| 15000000000 | 1 | 2019-08-07 06:30 | 2 |
| 15000000001 | 1 | 2019-08-07 07:07 | 1 |
| 15000000000 | 1 | 2019-08-07 08:07 | 1 |
| 15000000000 | 1 | 2019-08-08 08:07 | 1 |

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/590290

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX