簡體   English   中英

相互比較SQL結果行

[英]Compare SQL result rows with each other

我有一個需要相互比較的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 

並進行匹配。

關於我該怎么做的任何想法?

提前致謝。

流浪者

大多數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;

如果您的數據庫不支持窗口函數,則可以嘗試以下查詢:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM