0

我在尝试生成一个查询来显示客户姓名、联系电话、电子邮件地址和未付工作总和至少为 500 美元的任何客户的总未付工作成本时遇到了很多麻烦。

然后我必须对结果进行排序,以便最大的欠款位于顶部。

到目前为止,我已经提出了这个查询

SELECT 
  j.job_id, 
  c.name + c.surname, 
  c.phone, 
  c.email_address, 
  SUM(jt.cost * (DATEDIFF(mi, timestart, timecomplete)))
FROM client as c 
LEFT OUTER JOIN job AS j ON c.tax_file_number = c.tax_file_number
LEFT OUTER JOIN job_type AS jt ON j.jobtype_id = jt.jobtype_id
WHERE SUM(jt.cost * (DATEDIFF(mi, timecomplete, timestart) > 500
ORDER BY SUM(jt.cost * (DATEDIFF(mi, timecomplete, timestart))) DESC;

任何帮助,将不胜感激

4

3 回答 3

1

由于您的要求尚不清楚,因此在这里猜测,但我认为您想要这个:

WITH jobinfo as
(
   SELECT j.client_id, SUM(jt.cost * (DATEDIFF(mi, timecomplete, timestart))) as cost
   FROM job as j
   JOIN job_type as jt ON j.jobtype_id = jt.jobtype_id
   GROUP BY j.client_id
)
SELECT 
  c.client_id,
  c.name + c.surname, 
  c.phone, 
  c.email_address, 
  j.cost
FROM client as c 
JOIN jobinfo j ON c.client_id= j.client_id
WHERE j.cost > 500
ORDER BY j.cost DESC
于 2013-11-03T16:40:30.007 回答
0

请尝试以下方法。子句中不允许使用聚合函数(SUM,等) ,您应该使用这些函数。COUNTWHEREHAVING

SELECT 
  j.job_id, 
  c.name + c.surname, 
  c.phone, 
  c.email_address, 
  SUM(jt.cost * (DATEDIFF(mi, timestart, timecomplete)))
FROM client as c 
LEFT OUTER JOIN job AS j ON a.tax_file_number = c.tax_file_number
LEFT OUTER JOIN job_type AS jt ON j.jobtype_id = jt.jobtype_id
HAVING SUM(jt.cost * (DATEDIFF(mi, timecomplete, timestart) > 500
ORDER BY SUM(jt.cost * (DATEDIFF(mi, timecomplete, timestart))) DESC;

编辑: 固定ON a.tax_file_number = c.tax_file_number

于 2013-11-03T17:12:29.637 回答
0
declare _sum int, 

set _sum= (select SUM(jt.cost * (DATEDIFF(mi, timecomplete, timestart))) from job_type) SELECT j.job_id, c.name + c.surname, c.phone, c.email_address, SUM(jt.成本 * (DATEDIFF(mi, timestart, timecomplete))) FROM client as c 左外连接作业 AS j ON c.tax_file_number = c.tax_file_number 左外连接 job_type AS jt ON j.jobtype_id = jt.jobtype_id WHERE _sum > 500

于 2013-11-03T16:54:36.820 回答