简体   繁体   English

创建MySQL的列和行

[英]create columns and rows mysql

I have table data such as this 我有这样的表数据

index  user  date   rank
  11     a    1Mar    23
  12     b    1Mar    16
  13     a    2Mar    24
  14     b    2Mar    18

What I would like to achieve via a query is this: 我想通过查询实现以下内容:

    1Mar   2Mar
a   23     24
b   16     18 

I don't know if this can be done via a single statement at the command line or if this will have to be done via a form and some scripting. 我不知道这是否可以通过命令行中的单个语句来完成,或者是否必须通过表单和一些脚本来完成。 Doing through scripting I can do, but can't see how to do in a single statement. 通过脚本可以做到,但看不到如何在单个语句中完成。

you can do pivot like below, if you know all possible values for date or you need to use dynamic sql. 如果您知道日期的所有可能值,或者需要使用动态sql,则可以像下面这样进行数据透视。

SELECT user,
       MAX( CASE WHEN date ='1Mar' THEN rank else NULL end) AS '1Mar',
       MAX( CASE WHEN date ='2Mar' THEN rank else NULL end) AS '2Mar'
FROM Table1
GROUP BY user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM