使用变量和条件语句计算小时数的SQL查询输出错误

时间:2016-04-09 23:10:44

标签: sql-server if-statement

在所有5个查询中,这个是迄今为止对我来说最难的。我想得到这个输出:

  

本周的正常工作时数:544。     本周假期总时数:136。     本周的总OT时数:26。

但我得到了这个:

  

警告:聚合或其他SET操作消除了空值。   本周没有假期工资。

这是我的SQL代码:

 --Declare 5 int variables
   DECLARE @TotHours int, @TotEmps int, @HolHours int, @RegHours int, @OTHours int

--Set the Total Hours variable = to the sum total of workHours where the payperiod ID is most recent
SET @TotHours = (SELECT SUM(WorkHours) FROM Hours WHERE PPID = (SELECT MAX(PPID) FROM PayPeriod))

--Set the Holiday Hours variable = to the sum total of HolHours where the payperiod ID is most recent
SET @HolHours = (SELECT SUM(@HolHours) FROM Hours WHERE PPID = (SELECT MAX(PPID) FROM PayPeriod))

--Set the Total Employees variable = to the count of employee ID's where there is no TermDate
SET @TotEmps = (SELECT COUNT(EmpData.EmpID) FROM EmpData JOIN Work ON EmpData.EmpID = Work.EmpID WHERE EndDate IS NULL)

--Set the Regular Hours variable = to the Total Employees variable * 32
 SET @RegHours = (SELECT SUM(@TotEmps) * 32);


--(USE THIS CONDITIONAL STRUCTURE- substitute variable names where needed and remove the "--")
 IF @HolHours > 0
    BEGIN
        IF @RegHours > @TotHours
            BEGIN
            --set the Overtime Hours variable = 0
  SET @OTHours = 0
            --set the Regular Hours variable = Total Hours variable
  SET @RegHours = @TotHours

            --Place the 3 print statements here
  PRINT 'Total regular hours for the week: @TotHours.'
  PRINT 'Total holiday hours for the week: @HolHours.'
  PRINT 'Total OT Hours for the week: @OTHours.'
            END
        ELSE
            BEGIN
            --set the Overtime Hours variable = Total Hours variable - Regular Hours variable
  SET @OTHours = @TotHours - @RegHours

            --place the 3 print statements here

  PRINT 'Total regular hours for the week: @TotHours.'
  PRINT 'Total holiday hours for the week: @HolHours.'
  PRINT 'Total OT Hours for the week: @OTHours.'
            END
            END
ELSE 
    --Place the single print statement here (doesn't use variables)
  PRINT 'This week had no holiday pay.'

非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

假期的总和是错误的:

SET @HolHours = (SELECT SUM(@HolHours) FROM Hours WHERE PPID = (SELECT MAX(PPID) FROM PayPeriod))

也许这应该是:

SET @HolHours = (SELECT SUM(HolHours) FROM Hours WHERE PPID = (SELECT MAX(PPID) FROM PayPeriod))