|
2鱼币
现有一串代码如下:
- select case when nums is null then 0 else nums end nums from
- (select @num:=@num+1 nums from Transactions,(select @num:=-1) t1) t2
- where nums<=
- (select ifnull(max(transactions_count),0) num from
- (select count(amount) transactions_count from Transactions
- group by user_id,transaction_date) t3)
复制代码
该串代码希望实现的是统计Transactions表中在user_id和transaction_date分组下amount计数值中的最大值,之后生成一个从0到最大值的连续整数序列,如果Transactions表为空的时候,需要输出的是0,但实际这段代码输出的是一个空表。已经尝试加上ifnull判定条件输出0来改变这样的情况,但仍未解决,请指导一下应该如何改进?谢谢啦~
需要确保当 Transactions 表为空时,仍然能够生成一个包含 0 的结果集。
为此,我们可以通过外部查询来确保至少有一个值(即 0)被包含在最终的结果集中。
改进后的 SQL 代码:
- select case when nums is null then 0 else nums end as nums from (
- select @num:=@num+1 as nums from Transactions, (select @num:=-1) t1
- where @num <= (select coalesce(max(transactions_count), 0) as num from (
- select count(amount) as transactions_count from Transactions
- group by user_id, transaction_date) t3)
- union all
- select 0
- ) t2
- group by nums;
复制代码
|
最佳答案
查看完整内容
需要确保当 Transactions 表为空时,仍然能够生成一个包含 0 的结果集。
为此,我们可以通过外部查询来确保至少有一个值(即 0)被包含在最终的结果集中。
改进后的 SQL 代码:
|