在嵌套查询上获取错误

时间:2012-03-18 01:05:34

标签: sql sql-server database

我正在尝试在我的网站上开发一个时间表页面,这是我的数据库结构: enter image description here

我想获得总小时数(TimeSheetWeeks表的总和(timeFrom-timeTo)),总费用(TimeSheetWeeks表的总金额)和总数(TimSheetWeeks表的总金额+ compAllow表的总金额)。

这是我写的以获取结果的查询:

 ;WITH w(tot, tid, eid, fd, td, am, mw) AS
 (
 SELECT   Total = tsw.amount+ca.amount , tsw.[TimeSheetID], [EmployeeID], 
 [FromDate],[ToDate],  tsw.[Amount], SUM(DATEDIFF(MINUTE, [timeFrom],[timeTo] )) 
 FROM
 TimeSheet ts 
 INNER JOIN (
  SELECT  SUM(amount) amount, TimeSheetID 
  FROM TimeSheetWeeks
  GROUP BY TimeSheetID
  )  tsw ON ts.TimeSheetID = tsw.TimeSheetID INNER JOIN (
  SELECT  SUM(amount) amount, TimeSheetID
  FROM CompAllow
  GROUP BY TimeSheetID
  )  ca ON ts.TimeSheetID = ca.TimeSheetID INNER JOIN (
     SELECT  timeFrom, timeTo, TimeSheetID
  FROM TimeSheetWeeks
  ) AS tss ON tss.TimeSheetID=ts.TimeSheetID
  WHERE ts.TimeSheetID=6
  Group By tsw.[TimeSheetID], [EmployeeID], [FromDate], [ToDate], tsw.[Amount]
  )
  SELECT tot, tid, eid, fd, td, Amount = am,  totalHrs = RTRIM(mw/60) + ':' + 
  RIGHT('0'+ RTRIM(mw%60),2)
  FROM w;

此查询导致错误说

  

列'ca.amount'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

这里出了什么问题?提前完成。

2 个答案:

答案 0 :(得分:1)

错误说明了问题:

SELECT  SUM(amount) amount, TimeSheetID
  FROM CompAllow
  GROUP BY TimeSheetID
  )  ca ...

我不是百分百肯定,但我最初的建议是放弃本条款中的“分组依据”。充其量,它是多余的。

我还建议单独尝试每个子句 - 确保它们在语法上是正确的,确保它们返回预期的结果。

... IMHO

答案 1 :(得分:1)

ca.amount CTE中引用了w列,但GROUP BY子句中既未汇总也未包含此列:

 ;WITH w(tot, tid, eid, fd, td, am, mw) AS
 (
 SELECT   Total = tsw.amount+ca.amount , tsw.[TimeSheetID], [EmployeeID], 
 [FromDate],[ToDate],  tsw.[Amount], SUM(DATEDIFF(MINUTE, [timeFrom],[timeTo] )) 
 FROM
 TimeSheet ts 
 INNER JOIN (
  SELECT  SUM(amount) amount, TimeSheetID 
  FROM TimeSheetWeeks
  GROUP BY TimeSheetID
  )  tsw ON ts.TimeSheetID = tsw.TimeSheetID INNER JOIN (
  SELECT  SUM(amount) amount, TimeSheetID
  FROM CompAllow
  GROUP BY TimeSheetID
  )  ca ON ts.TimeSheetID = ca.TimeSheetID INNER JOIN (
     SELECT  timeFrom, timeTo, TimeSheetID
  FROM TimeSheetWeeks
  ) AS tss ON tss.TimeSheetID=ts.TimeSheetID
  WHERE ts.TimeSheetID=6
  Group By tsw.[TimeSheetID], [EmployeeID], [FromDate], [ToDate], tsw.[Amount]
  )
  SELECT tot, tid, eid, fd, td, Amount = am,  totalHrs = RTRIM(mw/60) + ':' + 
  RIGHT('0'+ RTRIM(mw%60),2)
  FROM w;

将其添加到GROUP BY或更改Total表达式,如下所示:

Total = tsw.amount + SUM(ca.amount)

取决于此查询的业务规则。