我将如何解决此查询?

时间:2016-03-18 14:25:29

标签: mysql sql

我桌子的简化版本:

 -------------------------------------------
| sender | recipient | date       | amount  |
 -------------------------------------------
| A      | B         | 2016-01-01 | 500.00  |
| C      | B         | 2016-01-02 | 600.00  |
| D      | C         | 2016-01-03 | 1025.00 |
| D      | D         | 2016-01-04 | 300.00  |
| D      | D         | 2016-01-05 | 300.00  |
| D      | D         | 2016-01-06 | 300.00  |
| D      | D         | 2016-01-07 | 300.00  |
| D      | D         | 2016-01-08 | 300.00  |
 -------------------------------------------

如何获得recipientOR LESS行至少amount 1024.00或更多?

不会D,因为它不会有3行超过amount 1024.00

预期结果:

 -----------
| recipient |
 -----------
| B         |
| C         |
 -----------

3 个答案:

答案 0 :(得分:1)

查询非常简单:

select recipient
from table
group by recipient
having count(*) <= 3 and sum(amount) >= 1024

答案 1 :(得分:0)

这很棘手。关键的观察是三个最高值的总和将超过1024,如果有的话,那么。

在MySQL中,您可以使用变量执行此操作:

select recipient, sum(amount) as amount_3
from (select t.*,
             (@rn := if(@r = recipient, @rn + 1,
                        if(@r := recipient, 1, 1)
                       )
             ) as rn
      from t cross join
           (select @r := '', @rn := 0) params
      order by recipient, amount desc
     ) t
where rn <= 3
group by recipient
having sum(amount) >= 1024;

答案 2 :(得分:0)

    <script type="text/javascript" class="init">

$(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );

    // DataTable
    var table = $('#example').DataTable();

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );

    </script>
相关问题