将一个reord移到顶部

时间:2016-07-25 06:35:28

标签: sql sql-server

我正在使用SQL Server。我有下表(标记为黄色)。我正处于这样的情况下生成输出(标记为绿色)。

enter image description here

查询中使用的条件:

  1. cal_wk为1时,target_hrs值应取自cal_wk 2
  2. target_hrs为空时,target_hrs应该是结果的最大值
  3. 我正在尝试像

    这样的案例陈述
    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

    提前感谢您的支持

1 个答案:

答案 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

在您对问题进行更新后,您需要将[表名]替换为该联接。