【问题标题】:mysql last 5 records in count statusmysql最后5条记录处于计数状态
【发布时间】:2020-08-21 04:11:24
【问题描述】:

预订表

id    status
1     booked
1     booked
3     cancelled
2     cancelled
2     booked
1     cancelled
1     cancelled
1     booked
select id, count(status) as tot_cancel 
from tbl_booking 
where id=1 and status='cancelled';

结果是

id    tot_cancel
1     2

但我需要用户 id = 1 的最后 5 条记录,并且取消计数不是取消的总表记录

【问题讨论】:

  • 最好举一个你想要的结果的例子
  • 没有任何排序数据可以让我们了解哪些记录是最后的。
  • @airmax 。 . .您可能应该问一个 问题。您的问题没有定义“最后一个”——SQL 表代表 unordered 集,因此除非列定义了排序,否则没有“最后一个”。此外,您应该显示您想要的结果集。

标签: mysql sql group-by count sql-order-by


【解决方案1】:

您可以使用limit 子句进行条件聚合:

select 1 as id, sum(status = 'cancelled')
from table t
where id = 1
order by ? -- use ordering column instead ?
limit 5;

您可以对所有ids 使用相关子查询:

select t.id, sum(t.status = 'cancelled')
from table t
where t.? in (select t1.? 
              from table t1 
              where t1.id = t.id 
              order by t1.? 
              limit 5
             )
group by t.id;

【讨论】:

    【解决方案2】:

    我了解您希望计算用户 1 的最后 5 条记录中取消的记录数。这是可能的,但您需要一个定义行顺序的列,因此哪些记录是最后一个是明确的.

    假设你的表中存在这样的列并且被称为ordering_id,你可以这样做:

    select sum(status = 'cancelled') no_cancelled
    from (select status from mytable where id = 1 order by ordering_id desc limit 5) t
    

    【讨论】:

    • 分析时发现1个错误。变量名称是预期的。 (靠近位置 110 的“?”) SQL 查询:文档 SELECT sum(status='cancelled') no_cancelled FROM(SELECT status from qry_booking WHERE id='3' order by ?limit 5)
    • @airmax:在我最初的回答中,? 代表了我在回答中提到的排序列。我更新了中间的查询以使其更加明确(但您仍然需要一个排序列)。
    • 为什么需要把t放在最后原因
    • @airmax:这是子查询的别名 - 它很重要且必须。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2022-10-01
    • 2018-10-17
    • 2019-12-28
    • 2012-02-13
    相关资源
    最近更新 更多