【问题标题】:how to show multiple row data into in a row mysql [duplicate]如何在一行mysql中显示多行数据[重复]
【发布时间】:2017-02-14 14:24:01
【问题描述】:

大家好,我是学习 MySQL 的新手,我有这张表

f_id|c_file|e.name|operation|rate|c_no | qty|
 1    015    A      coping   0.30  1    1300
 2    015    A      coping   0.30  2    4567
 3    015    A      coping   0.30  3    1300
 4    015    A      coping   0.30  4    789
 5    015    A      coping   0.30  5    47
 6    015    B      cutting  0.30  1    568
 7    015    B      cutting  0.30  2    123
 8    015    B      cutting  0.30  3    8952
 9    015    B      cutting  0.30  1    456
 10   015    B      cutting  0.30  2    89
 11   015    B      cutting  0.30  3    78

现在我想要这种形式的表格 表2

f_id|c_file|e.name|operation|c_no1|c_no2 |c_no3|c_no4|c_no5|total|rate|total*rate
 2     015  B       cutting 568     123   8952              9643  0.30 2892.9
 2     015  B       cutting 456     89    78                9643  0.30 2892.9
 total                      1024    212   9030

【问题讨论】:

  • 请把你试过的东西放在这里
  • 您可以简单地选择多个表。 SELECT table1.*, table2.* FROM table1, table2
  • 这被称为数据透视表,在 SO 上已被多次询问和回答。
  • 链接的副本描述了 MySQL 中的静态(预先知道附加字段的数量)和动态旋转(预先不知道字段的数量)。
  • 有人能告诉我如何按列求和

标签: mysql sql pivot-table


【解决方案1】:

您可以使用聚合来进行透视和用户变量以生成序列号。

set @fid := 0;

select @fid := @fid + 1 fid,
    c_file,
    e.name,
    operation,
    sum(case when c_no = 1 then qty end) c_no1,
    sum(case when c_no = 2 then qty end) c_no2,
    sum(case when c_no = 3 then qty end) c_no3,
    sum(case when c_no = 4 then qty end) c_no4,
    sum(case when c_no = 5 then qty end) c_no5,
    sum(qty) total,
    rate,
    sum(qty) * rate total_times_rate
from t
group by c_file,
    e.name,
    operation,
    rate
order by min(f_id);

【讨论】:

  • 非常感谢先生,您能否再告诉我一件事,如何对所有列求和,例如 (c_no1+c_no2+c_no3+c_no4+c_no5) 请...
  • @user3602024 - 请查看编辑
  • 再次感谢 gurv 先生......
  • 先生,此查询不适用于添加列的值!你能用 sum 再写一次完整的查询吗
  • 先生,我也编辑了这个问题先生,请给出答案,我知道我做得太糟糕了,但我必须问
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多