2

我对 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实现它看起来并不难,但我只是一个新手。任何帮助表示赞赏。

4

2 回答 2

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
于 2012-06-03T00:08:23.697 回答
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'
于 2012-06-03T00:03:38.223 回答