对于作业我必须添加三列表格(基本,附加人工和附加部分)以进行全面收费。然后我还必须确定找到的最小和最大总电量以及平均值。我成功地编写了一个总体充电查询
SELECT Service.ServiceId, Sum([BasicCharges]+[AdditionalLabourCharges]+
[AdditionalPartCharges]) AS [OverallCharge]
FROM Service
但是,我无法理解这些min,max和avg语句。我的草稿看起来像......但不起作用
SELECT MIN(OverallCharge) AS [MinOverallCharge],
MAX(OverallCharge) AS [MaxOverallCharge],
AVG(OverallCharge) AS [AverageOverallCharge]
FROM Service
WHERE Service
(SELECT Sum([S.BasicCharges]+[S.AdditionalLabourCharges]+[S.AdditionalPartCharges]) AS [OverallCharge]
FROM Service AS S);
非常感谢任何帮助。 感谢
尼克
答案 0 :(得分:0)
SELECT --get the min/avg/max of all charges
MIN(OverallCharge) AS [MinOverallCharge],
MAX(OverallCharge) AS [MaxOverallCharge],
AVG(OverallCharge) AS [AverageOverallCharge]
FROM
( -- calculate OverallCharge for each ServiceId
SELECT S.ServiceId,
Sum([S.BasicCharges]+[S.AdditionalLabourCharges]+[S.AdditionalPartCharges]) AS [OverallCharge]
FROM Service AS S
GROUP BY S.ServiceId
) dt;
答案 1 :(得分:0)
在这种情况下,子查询可以解决问题。使用您的第一个查询来获取每行的总和。然后你可以计算AVG,MIN和MAX:
SELECT
MIN(subquery.OverallCharge) AS [MinOverallCharge],
MAX(subquery.OverallCharge) AS [MaxOverallCharge],
AVG(subquery.OverallCharge) AS [AverageOverallCharge]
FROM
(
SELECT ([S.BasicCharges]+[S.AdditionalLabourCharges]+[S.AdditionalPartCharges])
AS [OverallCharge]
FROM Service AS S
) subquery;
答案 2 :(得分:0)
不要忘记GROUP BY
:
SELECT MIN(OverallCharge) AS [MinOverallCharge],
MAX(OverallCharge) AS [MaxOverallCharge],
AVG(OverallCharge) AS [AverageOverallCharge]
FROM
(SELECT ServiceId, Sum([S.BasicCharges]+[S.AdditionalLabourCharges]+
[S.AdditionalPartCharges]) AS [OverallCharge]
FROM Service AS S
GROUP BY ServiceId) dt;
子查询为每个OverallCharge
生成一个包含ServiceId
的表格,然后主要查询获得min
,max
,avg
。