首页 > 解决方案 > 计算由给定列分区的唯一不同值

问题描述

如何转换此输入表:

╔════════════════╦══════════════════════╗
║ 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

标签: sqlsql-server

解决方案


您需要一列来确定行的顺序,如果我正确理解了这个问题,以下方法是一种可能的解决方案。请注意,在示例中,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

推荐阅读