创建SQL查询以显示客户欠款

时间:2013-11-03 16:20:38

标签: sql-server

我在尝试生成一个显示客户名称,联系电话,电子邮件地址和任何未付工作总计(总和)至少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;

任何帮助将不胜感激

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

declare _sum int, 

设置_sum =(从job_type中选择SUM(jt.cost *(DATEDIFF(mi,timecomplete,timestart)))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 > 500

答案 2 :(得分:0)

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

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