Mysql查询带范围的案例,以及带货币的案例

Posted

技术标签:

【中文标题】Mysql查询带范围的案例,以及带货币的案例【英文标题】:Mysql query case with range, and case with currency 【发布时间】:2013-06-13 09:00:06 【问题描述】:

我有一个表格“订单”,其中的列看起来像这样:

| order_id | shop_id | order_total | currency | created_at |

现在我想做一个查询,它返回一个如下所示的表:

| interval | currency | sum |

其中interval 是日期间隔,currency 是货币,sum 是该时间间隔内所有订单的总和,该货币。例如:

| 2012-08-12-2012-09-12 | EUR | 540922 |

| 2012-08-12-2012-09-12 | DKK | 43215  |

| 2012-09-12-2012-10-12 | EUR | 123643 |

| 2012-09-12-2012-10-12 | DKK | 0      |

我已经有一个不考虑货币的查询,但我不知道如何让它考虑货币.. 有什么想法吗?

这是我现在使用的查询示例。真正的查询当然是代码生成的,这只是一个例子。

SELECT CASE
         WHEN created_at BETWEEN '2012-08-12' AND '2012-09-12' THEN '2012-08-12-2012-09-12'
         WHEN created_at BETWEEN '2012-09-12' AND '2012-10-12' THEN '2012-09-12-2012-10-12'
         WHEN created_at BETWEEN '2012-10-12' AND '2012-10-14' THEN '2012-10-12-2012-10-14'
       end AS intrvl,
       Sum(order_total)
FROM   `order` o
WHERE  shop_id = 4
       AND created_at BETWEEN '2012-08-12' AND '2012-11-17'
GROUP  BY CASE
            WHEN created_at BETWEEN '2012-08-12' AND '2012-09-12' THEN '2012-08-12-2012-09-12'
            WHEN created_at BETWEEN '2012-09-12' AND '2012-10-12' THEN '2012-09-12-2012-10-12'
            WHEN created_at BETWEEN '2012-10-12' AND '2012-10-14' THEN '2012-10-12-2012-10-14'
          end  

/莫腾

【问题讨论】:

【参考方案1】:

将货币添加到您的 select 和 group by 子句中

SELECT CASE
         WHEN created_at BETWEEN '2012-08-12' AND '2012-09-12' THEN '2012-08-12-2012-09-12'
         WHEN created_at BETWEEN '2012-09-12' AND '2012-10-12' THEN '2012-09-12-2012-10-12'
         WHEN created_at BETWEEN '2012-10-12' AND '2012-10-14' THEN '2012-10-12-2012-10-14'
       end AS intrvl,
       currency, 
       Sum(order_total)
FROM   `order` o
WHERE  shop_id = 4
       AND created_at BETWEEN '2012-08-12' AND '2012-11-17'
GROUP  BY CASE
            WHEN created_at BETWEEN '2012-08-12' AND '2012-09-12' THEN '2012-08-12-2012-09-12'
            WHEN created_at BETWEEN '2012-09-12' AND '2012-10-12' THEN '2012-09-12-2012-10-12'
            WHEN created_at BETWEEN '2012-10-12' AND '2012-10-14' THEN '2012-10-12-2012-10-14'
          end,
          currency

【讨论】:

好吧,这行得通,但现在我得到两行以 null 作为区间,因为它计算区间外的所有订单并将区间设置为空。有没有办法从查询? 只需确保您的 where 子句具有正确的 created_at 范围 - 它具有 2012-08-12 到 2012-11-17 但查询只查看到 2012-08-12 到 2012-10 的范围-14

以上是关于Mysql查询带范围的案例,以及带货币的案例的主要内容,如果未能解决你的问题,请参考以下文章

带计数的 SQL 案例语句?

三个案例带你看懂LayoutInflater中inflate方法两个参数和三个参数的区别

Xtrabackup使用案例

MyBatis完成代理方式查询数据以及核心文件配置

NLP将迎来黄金十年,7个案例带你入门(附Python代码)

带条件的 Oracle SQL 案例