0

我正在尝试使用 chartkick 显示一个多系列折线图,该折线图按月跟踪过去一年的总入站和出站物料流。

查询应生成类似于以下内容:

    SELECT SUM(ship_total_net_weight) AS sum_ship_total_net_weight,
    month(ship_date) AS month_ship_date, year(ship_date) 
    AS  year_ship_date 
    FROM [Downstream]
    WHERE is_active = 1 AND from_company_id = 89 
    AND
    (ship_date BETWEEN '2014-06-15 18:15:26.196' 
    AND '2015-06-15 18:15:26.196') 
    AND (to_company_id <> 89) 
    GROUP BY month(ship_date), year(ship_date)
    order By  year(ship_date), month(ship_date)

我的图表踢代码如下:

<%= line_chart [
              {name: "Inbound", data: Downstream.where(:to_company_id => current_user.company_id, :ship_date => 1.year.ago..Time.now).where('from_company_id <> ?', current_user.company_id ).group('month(ship_date), year(ship_date)').sum(:ship_total_net_weight)},
              {name: "Outbound", data: Downstream.where(:from_company_id => current_user.company_id, :ship_date => 1.year.ago..Time.now ).where('to_company_id <> ?', current_user.company_id ).group('month(ship_date), year(ship_date)').sum(:ship_total_net_weight)}
               ] %>

我从 chart kick 得到的结果是每个系列的一条线只有两个数据点,一个在 2013 年 12 月 31 日,一个在 2014 年 12 月 31 日。

对数据库运行上述 SQL 生成 9 个结果,范围从 6/2014 到 2/2015

为什么数据集不同?我的图表踢的语法错误吗?我需要以某种方式更改查询吗?

我在这里先向您的帮助表示感谢!

4

1 回答 1

0

我找到了解决方案,我的查询返回了单独的日期/月份列,因此我需要更改 group 子句,以下折线图可以正常工作:

<%= line_chart [
                {name: "Inbound", data: Downstream.where(:to_company_id => current_user.company_id, :ship_date => 1.year.ago..Time.now).where('from_company_id <> ?', current_user.company_id ).group('dateadd(month, datediff(month,1,ship_date),1)').sum(:ship_total_net_weight)},
                {name: "Outbound", data: Downstream.where(:from_company_id => current_user.company_id, :ship_date => 1.year.ago..Time.now ).where('to_company_id <> ?', current_user.company_id ).group('dateadd(month, datediff(month,1,ship_date),1)').sum(:ship_total_net_weight)}
                        ] %>

Using the dateadd and datediff functions in the group clause allows sorting by month/year of a date or date time field and returns the full date in a single column.

-Side note - I'm using SQLServer which is not supported by the groupdate gem that's often used on conjunction with chartkick.

于 2015-06-17T17:32:08.333 回答