我正在使用SQL Server。我有下表(标记为黄色)。我正处于这样的情况下生成输出(标记为绿色)。
查询中使用的条件:
cal_wk
为1时,target_hrs
值应取自cal_wk
2 target_hrs
为空时,target_hrs
应该是结果的最大值我正在尝试像
这样的案例陈述select
r.hour_val,
case
when us.calwk = 1
then 2
else us.calwk
end as cal_wk,
hrswk as target_hrs, u.uid
from
table1 us
inner join
users u on u.username = us.username
inner join
table2 r on u.uid = r.uid
where
us.yr = 2016
and u.uid = 2643
and r.cur_month = 7
and r.week_val = us.calwk
order by
us.calwk
这只是更改cal_wk
值而不是target_hrs
。
是否有人可以编写查询来生成expected_target_hrs
?
提前感谢您的支持
答案 0 :(得分:0)
尝试
Select
Case when calwk = 1 then wk2_max
When calwk = 0 then max
Else target_hrs end as expected_target_hours
From [table name]
Inner join
(Select max(case when calwk = 2 then target_hrs else 0 end) as wk2_max,
Max(target_hrs) as max
From [table name])
On 1 = 1
在您对问题进行更新后,您需要将[表名]替换为该联接。