我有一个返回以下信息的查询
ID Employees wk1 wk2 wk3 wk4
1 10 2 7 4 5
2 15 5 5 5 5
我想在此查询中添加另一个字段,该字段可以解决Weeksemployees。它可以通过查看Employees列并计算该数字可以满足多少wk来实现。示例如下所示;
ID Employees WeeksEmployees wk1 wk2 wk3 wk4
1 10 2 2 7 4 5
2 15 3 5 5 5 5
如果我能以任何方式实现这一目标,那将会非常有用。
答案 0 :(得分:1)
您可以执行以下操作,但如果您不想总是在第1周开始,那么您需要完全重复您的标准。
DECLARE @EmployeeWeekData TABLE
(
ID INT
, Employees INT
, wk1 INT
, wk2 INT
, wk3 INT
, wk4 INT
)
INSERT INTO @EmployeeWeekData
VALUES ( 1, 10, 2, 7, 4, 5 )
, ( 2, 15, 5, 5, 5, 5 )
SELECT *
, CASE WHEN Employees - ( wk1 + wk2 + wk3 + wk4 ) >= 0 THEN 4
WHEN Employees - ( wk1 + wk2 + wk3 ) >= 0 THEN 3
WHEN Employees - ( wk1 + wk2 ) >= 0 THEN 2
WHEN Employees - ( wk1 ) >= 0 THEN 1
ELSE 0
END AS WeeksFulfilled
FROM @EmployeeWeekData ewd
亲切的问候, CarrieAnne
答案 1 :(得分:1)
这将根据您的要求计算数字。
create table #demo (id int, employees int, wk1 int, wk2 int, wk3 int, wk4 int)
insert #demo values
(1,10,2,7,4,5),
(2,15,5,5,5,5)
select *, case
when wk1 + wk2 + wk3 + wk4 <= employees then 4
when wk1 + wk2 + wk3 <= employees then 3
when wk1 + wk2 <= employees then 2
when wk1 <= employees then 1 else 0 end as WeeksEmployees
from #demo
我可以想象您可能希望能够拥有更多的周数,因为您在IT中我假设您不想全部输入;)如果是这样,请让我知道要求,我会看到如果有适合的枢轴或动态解决方案。
答案 2 :(得分:0)
CREATE TABLE SAMPLE1
(
ID INT IDENTITY
,EMPLOYEES INT
,WK1 INT
,WK2 INT
,WK3 INT
,WK4 INT
)
INSERT INTO SAMPLE1 VALUES(10,2,7,4,5)
INSERT INTO SAMPLE1 VALUES(15,5,5,5,5)
INSERT INTO SAMPLE1 VALUES(12,15,5,5,5)
INSERT INTO SAMPLE1 VALUES(14,3,4,7,5)
INSERT INTO SAMPLE1 VALUES(20,5,5,5,5)
SELECT ID,EMPLOYEES,WK1,WK2,WK3,WK4
,CASE
WHEN WK1>EMPLOYEES THEN 0
WHEN WK1+WK2>EMPLOYEES THEN 1
WHEN WK1+WK2+WK3>EMPLOYEES THEN 2
WHEN WK1+WK2+WK3+WK4>EMPLOYEES THEN 3
ELSE 4
END AS WEEKSEMPLOYEES
FROM SAMPLE1