2016-08-10 1 views
2

私はこのようになりますテーブルがあります。同じIDを持つ特定の行をオフセットする方法 - MySQL?

id a.id b.id b.volume 
3  1  4359 3600 
4  1  5589 1300 
5  1  765  0 
8  2  7185 9900 
11 3  4616 3600 
12 3  4990 1900 
18 6  2885 368000 
19 6  3974 201000 
20 6  4793 135000 

id a.id b.id b.volume 
1  1  2605 9900 
2  1  345  8100 
3  1  4359 3600 
4  1  5589 1300 
5  1  765  0 
6  2  1438 22200 
7  2  5320 18100 
8  2  7185 9900 
9  3  1045 8100 
10 3  1928 8100 
11 3  4616 3600 
12 3  4990 1900 
13 4  5841 12100 
14 4  109  590 
15 5  6530 6600 
16 6  2202 1830000 
17 6  5014 450000 
18 6  2885 368000 
19 6  3974 201000 
20 6  4793 135000 

を私は私のような結果を得たい最低B.VOLUME

で2つ以上の同じA.IDを持つすべてのレコードを取得できますか

最高のB.A.VOLUMEを持つ同じA.IDを持つすべての2レコードを取り除きたい

申し訳ありませんが、説明するのは難しいので、おそらくこの表が役立ちます。削除する必要があるレコードは、大括弧[]で囲みます。

id a.id b.id b.volume 
[ 1  1  2605 9900  ] 
[ 2  1  345  8100  ] 
    3  1  4359 3600 
    4  1  5589 1300 
    5  1  765  0 
[ 6  2  1438 22200 ] 
[ 7  2  5320 18100 ] 
    8  2  7185 9900 
[ 9  3  1045 8100  ] 
[ 10 3  1928 8100  ] 
    11 3  4616 3600 
    12 3  4990 1900 
[ 13 4  5841 12100 ] 
[ 14 4  109  590  ] 
[ 15 5  6530 6600  ] 
[ 16 6  2202 1830000 ] 
[ 17 6  5014 450000 ] 
    18 6  2885 368000 
    19 6  3974 201000 
    20 6  4793 135000 

答えて

2

以下のクエリでは、あなたの期待した結果得られます:

set @num := 0, @group := ''; 

select id, aid, bid, bvolume from 
(
    select id, aid, bid, bvolume, 
     @num := if(@group = aid, @num + 1, 1) as row_number, 
     @group := aid as dummy 
    from TestingTable 
    order by aid, bvolume DESC 
) as x 
where x.row_number > 2; 

を私は、このサンプルデータは、手段が複数のテーブルを含むことができ、中央のデータである疑いがあるWorking DEMO

+0

ありがとうございました。 – whitesiroi

+1

@whitesiroiよろしくお願いします。お力になれて、嬉しいです。 – Arulkumar

2

を見つけてください。ここでは、このサンプルデータのソリューションを提供します:

select t2.`id`, t2.`a_id`, t2.`b_id`, t2.`b_volume` 
from (
    select 
     t1.*, @rowno := case when @grp = t1.a_id then @rowno + 1 else 1 end as rowno, @grp := t1.a_id as dummy 
    from (
     select * from middletable order by a_id, id 
    ) t1 
    join (select @rowno := 0, @grp := null) t 
) t2 
join (
    select max(b_volume) as b_volume, a_id from middletable group by a_id 
) t3 on t2.a_id = t3.a_id and t2.b_volume <> t3.b_volume 
where t2.rowno > 2 

Demo Here

+0

plus1ご協力いただきありがとうございます。 – whitesiroi

関連する問題