我有以下查询,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列,如下所示:
如何操作查询以使输出位于列中,因此我可以对其进行绘图。期望的输出如下:
一如既往的帮助,
更新以匹配OscarPérez的可能答案
答案 0 :(得分:1)
您可以使用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
答案 1 :(得分:0)
根据@JW,感谢您的帮助。
SELECT `month`,
MAX(CASE WHEN transporttype = 'Inbound' THEN loads ELSE NULL END) `Inbound`,
MAX(CASE WHEN transporttype = 'LocalGauteng' THEN loads ELSE NULL END) `LocalGauteng`,
MAX(CASE WHEN transporttype = 'LongDistance' THEN loads ELSE NULL END) `LongDistance`,
MAX(CASE WHEN transporttype = 'Shuttle-company1' THEN loads ELSE NULL END) `Shuttle-company1`,
MAX(CASE WHEN transporttype = 'Shuttle-company2' THEN loads ELSE NULL END) `Shuttle-company2`,
MAX(CASE WHEN transporttype = 'stores' THEN loads ELSE NULL END) `stores`,
MAX(CASE WHEN transporttype = 'returns' THEN loads ELSE NULL END) `returns`,
MAX(CASE WHEN transporttype = 'localkzn' THEN loads ELSE NULL END) `localkzn`
FROM
(
SELECT transporttype,
CONCAT(MONTHNAME(STR_TO_DATE(month, '%m')), ' ', year) AS `month`,
COUNT(loadnumber) AS loads
FROM v2ReportingTable
WHERE transporttype not in ('Extrusions-LongDistance','Extrusions-Shuttle') AND
urgent='no'
GROUP BY (concat(MONTHNAME(STR_TO_DATE(month, '%m')),' ',year)), transporttype
) aa
GROUP BY `month`