我是SQl的新手这是我的要求。
TableA
operation route measurement
A No 200
A Yes 300
B No 400
B Yes 500
我希望将其作为结果
Operation MeasurementNo MeasurementYes MeasureDifference
A 200 300 100
B 400 500 100
因此必须对操作字段进行分组。同时,操作测量的两个值必须合并为一行。
The MeasureDifference = MeasurementYes - MeasurementNo
。
使用SQL看起来并不难,但我只是一个新手。任何帮助表示赞赏。
答案 0 :(得分:3)
或者使用分组和条件聚合:
SELECT
operation,
SUM(CASE route WHEN 'No' THEN measurement END) AS MeasurementNo,
SUM(CASE route WHEN 'Yes' THEN measurement END) AS MeasurementYes,
SUM(CASE route WHEN 'Yes' THEN measurement END)
- SUM(CASE route WHEN 'No' THEN measurement END) AS MeasurementDifference
FROM atable t
GROUP BY
operation
答案 1 :(得分:2)
使用联接:
SELECT
MNo.operation AS Operation,
MNo.measurement AS MeasurementNo,
MYes.measurement AS MeasurementYes,
MYes.measurement - MNo.measurement AS MeasureDifference
FROM TableA AS MNo
JOIN TableA AS MYes
ON MNo.operation = MYes.operation
AND MNo.route = 'No'
WHERE MYes.route = 'Yes'