【问题标题】:How to transform following data table in another structure如何将以下数据表转换为另一种结构
【发布时间】:2014-01-27 19:41:04
【问题描述】:

我有以下数据表:

year, month,  customer, agent 
2013,  1,     abc,      yyyy 
2013,  2,     abc,      yyyy 
2013,  3,     abc,      zzzz 
2013,  4,     abc,      xxxx 
... 
2013,  12,    abc,      xxxx

我需要把这张表转换成这样的结构

year, from, to, customer, agent
2013, 1,    2   abc,      yyyy
2013, 3,    3   abc,      zzzz
2013, 4,    12  abc,      xxxx

所以我尝试使用 MAX 和 MIN 函数来识别客户和代理的 MIN 和 MAX 月份.. 但它不起作用。

你能帮帮我吗? 谢谢

【问题讨论】:

  • 确实想知道你尝试了什么!
  • 我忘了“分组”!

标签: mysql sql group-by max min


【解决方案1】:

试试这个:

SELECT A.year, 
       MIN(A.month) `from`,
       MAX(A.month) `to`, 
       A.customer, 
       A.agent
FROM tableA A
GROUP BY A.year,
         A.customer, 
         A.agent

查看SQL FIDDLE DEMO

输出

| YEAR | FROM | TO | CUSTOMER | AGENT |
|------|------|----|----------|-------|
| 2013 |    4 | 12 |      abc |  xxxx |
| 2013 |    1 |  2 |      abc |  yyyy |
| 2013 |    3 |  3 |      abc |  zzzz |

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多