doulai5585 2013-06-16 15:50
浏览 222
已采纳

在SQL中选择列值作为列标题?

I have a table like this:

------------------------------------------------------
ID  |   Date   |  ClientName  |  TransactionAmount   |
------------------------------------------------------
1   |  6/16/13 |  C1          |  15                  |
------------------------------------------------------
2   |  6/16/13 |  C1          |  10                  |
------------------------------------------------------
3   |  6/16/13 |  C2          |  10                  |
------------------------------------------------------
4   |  6/17/13 |  C2          |  20                  |
------------------------------------------------------

And I would like to get something like this:

------------------------------------------------------------------------
Date    |  C1_Total_Amount_Transacted   |  C2_Total_Amount_Transacted  |
------------------------------------------------------------------------
6/16/13 |            25                 |              10              |
------------------------------------------------------------------------
6/17/13 |            0                  |              20              |

In the second table Date is unique also I there are x clients in the databse the resul table will have x + 1 columns (1 fore date and x one for each client).

There might be necessary to write some PHP code and more querys, any working solution is perfect, I don`t need a full SQL solution.

Thanks

  • 写回答

1条回答 默认 最新

  • doumaque6551 2013-06-16 16:03
    关注

    I presume that you are rather new to SQL. This type of query requires conditional summation. And it is quite easy to express in SQL:

    select `date`,
           sum(case when Client_Name = 'C1' then TransactionAmount else 0 end) as C1,
           sum(case when Client_Name = 'C2' then TransactionAmount else 0 end) as C2
    from t
    group by `date`
    

    But, you have to list each client in the query. You always have to specify the exact column headers for a SQL query. If you don't know them, then you need to create the SQL as a string and then execute it separately. This is a rather cumbersome process.

    You can often get around that by using group_concat(). This puts the values in a single column, with a separator of your choice (default is a comma):

    select `date`, group_concat(amount)
    from (select `date`, ClientName, sum(TransactionAmount) as amount
          from t
          group by `date`, ClientName
         ) t
    group by `date`
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,