mysql查询将行输出到列

标签 mysql

我的以下查询 100% 有效。

SELECT
transporttype,
concat(MONTHNAME(STR_TO_DATE(month, '%m')), ' ', year) AS `month`,
round(sum(cost),0) AS cost
FROM v2ReportingTable
WHERE (transporttype not in ('Extrusions-LongDistance','Extrusions-Shuttle') and urgent='no')
GROUP BY (concat(MONTHNAME(STR_TO_DATE(month, '%m')),' ',year)),transporttype
ORDER BY (concat(MONTHNAME(STR_TO_DATE(month, '%m')),' ',year)), transporttype

这会在 1 列中输出结果,如下所示:

enter image description here

我怎样才能操纵查询,使输出在列中,这样我就可以绘制它。所需的输出如下:

enter image description here

一如既往的帮助,

已更新以匹配 Oscar Pérez 的可能答案

enter image description here

最佳答案

您可以使用 LEFT JOIN 运算符。例如:

SELECT s0.month, 
       s1.cost as Inbound, 
       s2.cost as LocalPMB,
       s3.cost as Shuttle,    
       s4.cost as LongDistance
  FROM (
         SELECT 1 as month
          UNION
         SELECT 2 as month
          UNION
         SELECT 3 as month
          UNION
         SELECT 4 as month
          UNION
         SELECT 5 as month
          UNION
         SELECT 6 as month
          UNION
         SELECT 7 as month
          UNION
         SELECT 8 as month
          UNION
         SELECT 9 as month
          UNION
         SELECT 10 as month
          UNION
         SELECT 11 as month
          UNION
         SELECT 12 as month
       ) as s0
LEFT JOIN
       (
         SELECT month,
                round(sum(cost),0) AS cost
           FROM v2ReportingTable
          WHERE urgent='no'
            AND transporttype='Inbound'
       GROUP BY month
       ) as s1 on s0.month=s1.month
LEFT JOIN
       (
         SELECT month,
                round(sum(cost),0) AS cost
           FROM v2ReportingTable
          WHERE urgent='no'
            AND transporttype='LocalPMB'
       GROUP BY month
       ) as s2 on s0.month=s2.month
LEFT JOIN
       (
         SELECT month,
                round(sum(cost),0) AS cost
           FROM v2ReportingTable
          WHERE urgent='no'
            AND transporttype='Shuttle'
       GROUP BY month
       ) as s3 on s0.month=s3.month
LEFT JOIN
       (
         SELECT month,
                round(sum(cost),0) AS cost
           FROM v2ReportingTable
          WHERE urgent='no'
            AND transporttype='Long Distance'
       GROUP BY month
       ) as s4 on s0.month=s4.month
ORDER BY month

关于mysql查询将行输出到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14520046/

相关文章:

php - echarts:从URL获取数据

mysql - JDBC 与 Mysql : using mulitple outer joins with where clauses

mysql - 左外加入 rails

php - 用其他数组中的值填充数组中的空值

mysql - 如何在表中找不到数据时将计数设为 0?

java - 为什么 MySQL 会提示此查询中的未知列?

php - $_SERVER ['HTTP_REFERER'];尝试制作引用脚本时返回 .css 文件

c# - Web-api和Kestrel访问本地MySql服务器时得到空连接

php - 存储信息故障

MYSQL - ORDER BY 有条件的两个字段