以下是我努力实现的一个例子:
表A:
| type | message | createdAt |
|:----------:|:---------:|:--------------------------:|
| create | awesome | 2017-07-21 11:20:35.147629 |
| create | hello | 2017-07-21 11:20:35.147629 |
| create | good | 2017-07-22 10:20:34.123331 |
| upload | nope | 2017-07-22 11:28:08.815828 |
| create | test | 2017-07-22 11:29:35.147629 |
| create | hello | 2017-07-22 12:20:35.147629 |
期望输出:
| type | new_message | new_createdAt |
|:------:|:------------:|:--------------------------:|
| create | 3 | 2017-07-22 10:20:34.123331 |
| upload | nope | 2017-07-22 11:28:08.815828 |
| create | 2 | 2017-07-22 12:20:35.147629 |
只有当SQL语句按
type
的顺序排列时,它们才应该合并类似的createdAt
。如果序列中相似的type
值的数目大于1,那么new_message
就是count elsenew_message
与message
相同(这个If else子句不是最重要的特性,只给出count的语句也可以)。谢谢您。
更新
是否有可能在时间序列中加入另一个因素,只有当最低值和最高值之间的差异
createdAt
为X时,才进行分组。例如,如果我选择X=24小时,表A的输出将更改为:
| type | new_message | new_createdAt |
|:------:|:------------:|:--------------------------:|
| create | 2 | 2017-07-21 11:20:35.147629 |
| create | good | 2017-07-22 10:20:34.123331 |
| upload | nope | 2017-07-22 11:28:08.815828 |
| create | 2 | 2017-07-22 12:20:35.147629 |
有没有办法在没有
JOIN
的情况下这样做。 最佳答案
您可以使用ROW_NUMBER
s的差异:
WITH CteRn AS(
SELECT *,
ROW_NUMBER() OVER(ORDER BY createdAt)
- ROW_NUMBER() OVER(PARTITION BY type ORDER BY createdAt) AS rn
FROM Tbl
)
SELECT
type,
CASE
WHEN COUNT(*) > 1 THEN CAST(COUNT(*) AS VARCHAR(30))
ELSE MAX(cte.message)
END AS message,
MAX(cte.createdAt) AS createdAt
FROM CteRn cte
GROUP BY cte.type, cte.rn
ORDER BY MAX(cte.createdAt);
ONLINE DEMO