我的以下查询 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 列中输出结果,如下所示:
我怎样才能操纵查询,使输出在列中,这样我就可以绘制它。所需的输出如下:
一如既往的帮助,
已更新以匹配 Oscar Pérez 的可能答案
最佳答案
您可以使用 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/