【问题标题】:Query a table so that data in one column could be shown as different fields查询一张表,以便一列中的数据可以显示为不同的字段
【发布时间】:2018-05-28 10:55:08
【问题描述】:

我有一个存储客户服务数据的表。表/视图具有以下结构。

    userid  calls_received    calls_answered    calls_rejected   call_date  
-----------------------------------------------------------------------  
    1030        134              100              34             28-05-2018  
    1012        140              120              20             28-05-2018  
    1045        120              80               40             28-05-2018  
    1030        99               39               50              28-04-2018  
    1045        50               30               20             28-04-2018  
    1045        200              100              100            28-05-2017  
    1030        160               90              70             28-04-2017  
    1045        50               30               20             28-04-2017    

这是示例数据。数据按天存储。
我必须在以日期为输入的报表设计器软件中创建一个报表。当用户选择例如日期时。 2018 年 5 月 28 日。该日期作为参数 ${call_date} 发送。我必须以这样的方式查询视图,结果应该如下所示。如果用户选择日期 28/05/2018,则 28/04/2018 和 28/05/2017 的数据应并排显示,如下列顺序。

    userid | cl_cur | ans_cur | rej_cur |success_percentage |diff_percent|position_last_month| cl_last_mon | ans_las_mon | rej_last_mon |percentage_lm|cl_last_year | ans_last_year | rej_last_year
    1030   | 134    |  100    |  34     |      74.6 %       |  14%       |   2               |      99     |   39        |      50      |  39.3%      | 160         |  90           |  70   
    1045   | 120    |  80     |  40     |      66.6%        |  26.7%     |     1             |      50     |   30        |      20      |   60%       | 50          |  30           |  20   

此查询的目的是在列中显示所选日期的数据、上个月同一天的数据和往年同一天的数据,以便用户查看和比较。此处结果按所选日期的百分比(ans_cur/cl_cur)按计算百分比的降序排列,并显示在 success_percentage 下。
列 position_last_month 是该特定员工在上个月的职位,按百分比降序排列。在此示例中,用户 ID 1030 上个月排名第二,用户 ID 1045 上个月排名第一。同样,我也必须计算这一年。
还有一个名为 diff_percent 的字段,它计算上个月处于同一位置的人之间的百分比差异。我去年也必须这样做。我怎样才能达到这个结果。请帮忙。

【问题讨论】:

  • 您的谷歌搜索字符串是“sql server pivot query”。

标签: sql sql-server view pivot pentaho-report-designer


【解决方案1】:

这回答了问题的原始版本。

一种方法是join

select t.user_id, 
       t.calls_received as cr_cur, t.calls_answered as ca_cur, t.calls_rejected as cr_cur,
       tm.calls_received as cr_last_mon, tm.calls_answered as ca_last_mon, tm.calls_rejected as cr_last_mon,
       ty.calls_received as cr_last_year, ty.calls_answered as ca_last_year, ty.calls_rejected as cr_last_year
from t left join
     t tm
     on tm.userid = t.userid and
        tm.call_date = dateadd(month, -1, t.call_date) left join
     t ty
     on ty.userid = t.userid and
        tm.call_date = dateadd(year, -1, t.call_date)
where t.call_date = ${call_date};

【讨论】:

  • 非常感谢您的解决方案。这真的对我有用。但我有更多的要求。我已经编辑了这个问题。你能帮忙吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
相关资源
最近更新 更多