在这种特殊情况下,使用起来不是更容易WHERE
吗?
SELECT SUM(WTE) AS `Band6_WTE`
FROM `orthoptists` AS o
LEFT JOIN `instances` AS i
ON o.instance_FK = i.id
WHERE i.region = 14
AND band = "E"
对于一般情况,您可以使用,GROUP BY
因为您说您需要每个波段的结果(列波段中的每个值):
SELECT band, SUM(WTE) AS `WTE`
FROM `orthoptists` AS o
LEFT JOIN `instances` AS i
ON o.instance_FK = i.id
WHERE i.region = 14
GROUP BY band
这将给出 NULL 或 0,如果您愿意,您可以使用IFNULL
将 NULL 转换为 0:
IFNULL(SUM(WTE), 0)
编辑:正如您在评论中指出的那样,您希望不同波段的多列而不是多行。一般来说,您不应该从 SQL 中执行此操作(使用第二个查询并从您的代码中执行枢轴操作),但也有例外情况,在 SQL 之外执行此操作要复杂得多,因此您可以这样做:
SELECT
(SELECT SUM(WTE)
FROM `orthoptists` AS o
LEFT JOIN `instances` AS i
ON o.instance_FK = i.id
WHERE i.region = 14
AND band = "E") AS `Band6_WTE`,
(SELECT SUM(WTE)
FROM `orthoptists` AS o
LEFT JOIN `instances` AS i
ON o.instance_FK = i.id
WHERE i.region = 14
AND band = "F") AS `Band7_WTE`,
(SELECT SUM(WTE)
FROM `orthoptists` AS o
LEFT JOIN `instances` AS i
ON o.instance_FK = i.id
WHERE i.region = 14
AND band = "G") AS `Band8_WTE`
精确的语法可能需要一些调整(有些数据库要求每个SELECT
都包含一个FROM
子句,有些可能需要子选择中的每一列的名称,我认为 MySQL 没有,但我现在无法检查),但是无论如何,该原则都应适用。