将SQL结果行相互比较

时间:2013-08-19 14:15:42

标签: sql database compare resultset

我有一个sql查询的结果集,我需要相互比较。

示例:

ID |  VALUE  |  Comment | sort | store | price
 1    test       main      des    f1       5
 2    each       sec       asc    f2       10
 3    test       main      des    f1       12

现在从结果集中我只需要获取值,注释,排序和存储相同的行。

像:

 ID |  VALUE  |  Comment | sort | store | price
  1    test       main      des     f1      5
  3    test       main      des     f1      12

所以我需要改变

select id, value, comment, sort, store, price from test.table 

并进行匹配。

关于我如何做到这一点的任何想法?

提前致谢。

TheVagabond

2 个答案:

答案 0 :(得分:2)

大多数SQL数据库都支持窗口函数。你可以这样做:

select id, value, comment, sort, store, price
from (select t.*,
             count(*) over (partition by value, comment, sort, store) as cnt
      from t
     ) t
where cnt > 1;

答案 1 :(得分:1)

如果您的数据库不支持窗口功能,您可以尝试以下查询:

select
    *
from
    (
        select
            value, comment, sort, store
        from
            test
        group by
            value, comment, sort, store
        having count(*) > 1
    ) as t
    inner join test on (
        test.value = t.value and test.sort = t.sort and test.сomment = t.сomment and test.store = t.store
    )

但我建议你另外输出“彼此”比较:

select
    t1.id, t2.id, t1.VALUE, t1.sort, t1.store, t1.price, t2.price
from
    test t1
    join test t2 on (t2.id > t1.id and t1.value = t2.value and t1.sort = t2.sort and t1.store = t2.store and t1.comment = t2.comment)