1

返済が属するローンごとに 16 行の返済テーブルがあります。

Repayments
loanid  repid  amnt
--------------------
a1      r1     1,100
a1      r2     1,100
|       |      |
a1      r16    1,105
b2      s1     2,500
b2      s2     2,500
|       |      |
b2      s16    2,510
|       |      |

Loans
loanid  othercolumns...
-----------------------
a1
b2
|
blahid
|

LoanIds は文字列です。返済IDも

すべてのローンの各返済から最初の 15 行を取得するクエリを探しています。

loanid  repid  amnt
a1      r1     1,100
a1      r2     1,100
|       |      |
a1      r15    1,105
b2      s1     2,500
b2      s2     2,500
|       |      |
b2      s15    2,510
|       |      |

これはSQLで可能ですか?もしそうなら、どのように?

4

2 に答える 2

2

rep が連続していないと仮定すると、その場合は を使用できWHERE rep <= 15、グループごとに行番号を導入する必要があります。MySql には、他のデータベースのような組み込みの行番号関数はありませんがuser defined variables、同じ結果を得るために使用できます

select *
from (
  select loan, rep, amnt, @row:=if(@prevLoan=loan, @row+1, 1) rn, @prevLoan:=loan
  from repayments
    join (select @row:=0, @prevLoan:=0) t
  order by loan, rep
  ) t
where rn <= 15
于 2013-07-02T01:12:13.290 に答える
0

他のテーブルに何らかの ID がある場合は、単純な内部結合でうまくいくはずです。次のようなものです。

select t1.column1, t1.column2 
from table1 t1 
inner join table2 t2 on t1.id = t2.t1id
limit 15

列とテーブル名を投稿しない場合は、それが得られることを願っています。必要なクエリを提供しようとすることができますが、これで開始できます。

于 2013-07-02T01:10:46.407 に答える