我有一个C#应用程序,用于从SQL数据库导出数据。它从视图中提取数据并将其导出到Excel以导入到我们的工资单系统。我需要计算加班金额。我有以下代码,但它不计算加班的数量。我在互联网上搜索了一个解决方案,但没有任何运气。
SELECT [Co Code]
, [Empl No]
, [Task CD]
, [Day No]
, [Fund Co Code]
, [Job No]
, [Equip Cost Cde]
, SUM([Reg Hrs Jc]) AS [Reg Hrs Jc]
,(CASE WHEN [Reg Hrs Jc] > 40 THEN [Reg Hrs Jc] - 40 ELSE 0 END) AS [Ot Hrs Jc]
FROM dbo.MIS_FTTIMECARD_OT
WHERE ([Date Worked] BETWEEN '8/11/2013' AND '8/17/2013')
GROUP BY [Co Code]
, [Empl No]
, [Task CD]
, [Day No]
, [Fund Co Code]
, [Job No]
, [Equip Cost Cde]
, (CASE WHEN [Reg Hrs Jc] > 40 THEN [Reg Hrs Jc] - 40 ELSE 0 END)
答案 0 :(得分:0)
您应该使用子查询,这将允许您首先总结工作时间:
SELECT t.*, (CASE WHEN [Reg Hrs Jc] > 40 THEN [Reg Hrs Jc] - 40 ELSE 0 END) AS [Ot Hrs Jc]
FROM
(SELECT [Co Code], [Empl No], [Task CD], [Day No], [Fund Co Code], [Job No], [Equip Cost Cde], SUM([Reg Hrs Jc]) AS [Reg Hrs Jc] FROM dbo.MIS_FTTIMECARD_OT
WHERE ([Date Worked] BETWEEN '8/11/2013' AND '8/17/2013')
GROUP BY [Co Code], [Empl No], [Task CD], [Day No], [Fund Co Code], [Job No], [Equip Cost Cde]) AS t
答案 1 :(得分:0)
为了扩展其他人的答案,你的命名惯例可能会导致混淆。
考虑以下代码片段:
, SUM([Reg Hrs Jc]) AS [Reg Hrs Jc]
,(CASE WHEN [Reg Hrs Jc] > 40 THEN [Reg Hrs Jc] - 40 ELSE 0 END) AS [Ot Hrs Jc]
通过重命名,可以清楚地知道发生了什么:
, SUM([Reg Hrs Jc]) AS [Reg Hrs Jc Sum]
,(CASE WHEN [Reg Hrs Jc] > 40 THEN [Reg Hrs Jc] - 40 ELSE 0 END) AS [Ot Hrs Jc]
我认为您已经有效地尝试执行以下操作,如果它没有共享实际的列名,则无法正常工作
, SUM([Reg Hrs Jc]) AS [Reg Hrs Jc Sum]
,(CASE WHEN [Reg Hrs Jc Sum] > 40 THEN [Reg Hrs Jc Sum] - 40 ELSE 0 END) AS [Ot Hrs Jc]
你不能昵称一个列,然后用同一范围内的新标题引用它,所以你应该像其他人建议的那样将Ot Hrs Jc建立在SUM([Reg Hrs Jc])上。