sql - 计算由给定列分区的唯一不同值
问题描述
如何转换此输入表:
╔════════════════╦══════════════════════╗
║ conversationId ║ LengthOfCOnversation ║
╠════════════════╬══════════════════════╣
║ 1 ║ 1 ║
║ 1 ║ 2 ║
║ 1 ║ 2 ║
║ 1 ║ 5 ║
║ 1 ║ 5 ║
║ 1 ║ 5 ║
║ 1 ║ 5 ║
║ 1 ║ 5 ║
║ 1 ║ 1 ║
║ 1 ║ 3 ║
║ 1 ║ 3 ║
║ 1 ║ 3 ║
║ 2 ║ 1 ║
║ 2 ║ 2 ║
║ 2 ║ 2 ║
║ 3 ║ 2 ║
║ 3 ║ 2 ║
║ 4 ║ 1 ║
╚════════════════╩══════════════════════╝
到sql中的以下输出:
╔════════════════╦══════════════════════╗
║ conversationId ║ LengthOfCOnversation ║
╠════════════════╬══════════════════════╣
║ 1 ║ 1 ║
║ 1 ║ 2 ║
║ 1 ║ 5 ║
║ 1 ║ 1 ║
║ 1 ║ 3 ║
║ 2 ║ 1 ║
║ 2 ║ 2 ║
║ 3 ║ 2 ║
║ 4 ║ 1 ║
╚════════════════╩══════════════════════╝
我们正在尝试LengthOfConversation
将输入中的相同分组到一个 per conversationId
。
解决方案
您需要一列来确定行的顺序,如果我正确理解了这个问题,以下方法是一种可能的解决方案。请注意,在示例中,Id
列确定行的顺序。
桌子:
CREATE TABLE Data (
Id int IDENTITY(1, 1),
ConversationId int,
LenOfConversation int
)
INSERT INTO Data
(ConversationId, LenOfConversation)
VALUES
(1, 1),
(1, 2),
(1, 2),
(1, 5),
(1, 5),
(1, 5),
(1, 5),
(1, 5),
(1, 1),
(1, 3),
(1, 3),
(1, 3),
(1, 3),
(1, 2)
陈述:
SELECT
ConversationId, LenOfConversation
FROM (
SELECT
Id,
ConversationId,
LenOfConversation,
LAG(LenOfConversation) OVER (PARTITION BY ConversationId ORDER BY Id) AS LenOfConversation_Prev
FROM Data
) t
WHERE (LenOfConversation_Prev IS NULL) OR (LenOfConversation <> LenOfConversation_Prev)
ORDER BY Id
结果:
ConversationId LenOfConversation
1 1
1 2
1 5
1 1
1 3
1 2
推荐阅读
- html-framework-7 - 如何在本地运行和测试 Framework7 应用程序?
- swift - 如何让我的应用程序打印“电子邮件发送”或“电子邮件已取消”?
- latex - 乳胶词汇表不会出现
- c# - EFCore Add Entity with childEntity Throw 已跟踪相同的键
- python - 通过docker CE桌面(windows)上的批处理文件运行多个python程序
- android - 如何检查用户在登录表单上输入的电子邮件用户是否存在于firebase中
- xaml - 如何在 2 行 TextBlock 中换行?
- css - 我正在尝试在移动预览的正面屏幕上获得号召性用语按钮,而不更改 Web 布局
- javascript - 传递动态数据 Victory-native 图表
- excel - Pentaho Report Designer:如果输出格式为 excel,则更改列值