【问题标题】:T-SQL Find first occurrence of unique combinationsT-SQL 查找第一次出现的唯一组合
【发布时间】:2015-11-30 19:23:08
【问题描述】:

我有一张像这样的表

Log_ID  User_ID  Line   Attribute
1       A        1      **** 
1       B        2      ****
1       B        3      ****
2       C        1      ****
2       C        2      ****
2       A        3      ****
2       B        4      ****

对于每个 Log_ID,User_ID 和 Line 中有多个值。 (Log_ID, Line) 将始终是唯一的,但 (Log_ID, User_ID) 不会。

我正在尝试返回唯一的 (Log_ID, User_ID) 对,其中最低 Line 值是决胜局。结果集如下所示:

Log_ID  User_ID  Line   Attribute
1       A        1      ****
1       B        2      ****
2       C        1      **** 
2       A        3      ****
2       B        4      ****

我尝试过的任何方法都没有奏效。我要么获取唯一的(Log_ID、User_ID、Line)三元组,要么只获取 Line=1 的行。

除了 Log_ID、User_ID 和 Line 之外,我还需要表中的其他属性,所以我不能只使用 SELECT DISTINCT

有什么想法吗?我找到的解决方案通常假设我正在尝试加入到表中并且我想加入最低匹配。但这是我的主表。

谢谢!

【问题讨论】:

    标签: sql sql-server tsql unique


    【解决方案1】:

    这种类型的优先级可以很好地利用row_number()

    select t.*
    from (select t.*,
                 row_number() over (partition by log_id, user_id
                                    order by line) as seqnum
          from t
         ) t
    where seqnum = 1;
    

    编辑:

    可以也可以通过加入最低匹配或使用相关子查询来做到这一点。例如:

    select t.*
    from t
    where t.line = (select min(t2.line)
                    from t t2
                    where t2.log_id = t.log_id and t2.user_id = t.user_id
                   );
    

    row_number() 通常更快。

    【讨论】:

    • 加入最低匹配就像一种魅力,而且比 row_number() 快得多。谢谢!
    • @Avyncentia 。 . .有趣的数据点。 row_number() 通常更快,但并非总是如此。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    相关资源
    最近更新 更多