【发布时间】:2022-01-19 19:22:08
【问题描述】:
我正在尝试从具有有效唯一/主键的表生成结果集,例如 billyear、billmonth 和 type 以及成本和消耗。因此可能有 3 个账单年份和账单月份相同的条目,但类型可能是以下三个值之一:E、W 或 NG。
我需要创建一个每个账单年和账单月条目只有一行的结果集。
(
select month as billmonth, year as billyear, cost_estimate as eleccost, consumption_estimate as eleccons from tblbillforecast where buildingid=19 and type='E'
)
UNION (
select month as billmonth, year as billyear, cost_estimate as gascost, consumption_estimate as gascons from tblbillforecast where buildingid=19 and type='NG'
)
UNION (
select month as billmonth, year as billyear, cost_estimate as watercost, consumption_estimate as watercons from tblbillforecast where buildingid=19 and type='W'
)
这会生成一个仅包含 billmonth、billyear、eleccost 和 eleccons 列的结果集。我尝试了各种解决方案,但上面的示例最简单地说明了哪里出了问题。
此外,每个账单月/账单年的唯一组合仍然有 3 行,而不是合并为一个。
SELECT month AS billmonth,
year AS billyear,
SUM(CASE type WHEN 'E' THEN cost_estimate END) AS eleccost,
SUM(CASE type WHEN 'NG' THEN cost_estimate END) AS gascost,
SUM(CASE type WHEN 'W' THEN cost_estimate END) AS watercost
FROM tblbillforecast
WHERE buildingid=19
GROUP BY billmonth, billyear;
预期结果,例如:
年 |月 |电费 |煤气费|水费
2018 | 1 | 32800 | 4460 | 4750
【问题讨论】:
-
始终忽略除第一个子查询中的别名之外的所有别名。使用条件聚合。
-
我建议您不要发布数据截图(即discouraged in the Stack Overflow guide),而应该在dbfiddle.uk 上创建一个可重现的测试用例。