2013-10-21 56 views
1

我有了2列的表,我试图更新基于这些标准的另一个表:更新查询与条件在SQL

  1. 设置标志,以“好”在最重复键对于同一GROUP_KEY Main_Key列(请注意,我们可以有任何GROUP_KEY不同Main_Keys)
  2. 设置标志,以“坏”在Main_Key列中至少重复键为同一GROUP_KEY
  3. 设置标志,以“唐” t使用'如果不同的Main_Keys对于相同的GROUP_KEY是相等的

这里是我的表

GROUP_KEY MAIN_KEY 
22   4 
22   4 
22   55 
22   55 
22   55 
22   55 
10   10 
10   10 
18   87 
18   22 
18   22 

这里是预期结果的UPDATE

GROUP_KEY MAIN_KEY   FLAG 
    22   4   Bad 
    22   4   bad 
    22   55   Good 
    22   55   Good 
    22   55   Good 
    22   55   Good 
    10   10   Don't Use 
    10   10   Don't Use 
    18   87   Bad 
    18   22   Good 
    18   22   Good 

后,我只知道怎么做只是正常的更新查询,但没有,甚至开始这个逻辑。日Thnx的帮助

+0

为什么18- 87不好? –

+0

感谢您的询问,因为我只考虑在Main_Key中对于同一Group_Key具有最多重复编号时的良好。如果你看它,数字22显示两次,和87显示只有一次相同的组密钥。 – moe

回答

2

用途:

declare @t table(GROUP_KEY int, MAIN_KEY int) 

insert @t values 
(22, 4), 
(22, 4), 
(22, 55), 
(22, 55), 
(22, 55), 
(22, 55), 
(10, 10), 
(10, 10), 
(18, 87), 
(18, 22), 
(18, 22) 

select t.*, b.flag 
from @t t 
join 
(
    select a.GROUP_KEY, a.MAIN_KEY 
     , 
      case 
       when a.GROUP_KEY = a.MAIN_KEY 
        then 'Don''t Use' 
       when a.count = MAX(a.count) over(partition by a.GROUP_KEY) 
        then 'Good' 
       else 'Bad' 
      end [flag] 
    from 
    (
     select t.GROUP_KEY, t.MAIN_KEY, COUNT(*) [count] 
     from @t t 
     group by t.GROUP_KEY, t.MAIN_KEY 
    )a 
)b 
on b.GROUP_KEY = t.GROUP_KEY and b.MAIN_KEY = t.MAIN_KEY 

输出:

GROUP_KEY MAIN_KEY flag 
----------- ----------- --------- 
10   10   Don't Use 
10   10   Don't Use 
18   22   Good 
18   22   Good 
18   87   Bad 
22   4   Bad 
22   4   Bad 
22   55   Good 
22   55   Good 
22   55   Good 
22   55   Good 

更新: 假设你有你的表flag列:

update @t 
set flag = b.flag 
from @t t 
join 
(
    select a.GROUP_KEY, a.MAIN_KEY 
     , 
      case 
       when a.GROUP_KEY = a.MAIN_KEY 
        then 'Don''t Use' 
       when a.count = MAX(a.count) over(partition by a.GROUP_KEY) 
        then 'Good' 
       else 'Bad' 
      end [flag] 
    from 
    (
     select t.GROUP_KEY, t.MAIN_KEY, COUNT(*) [count] 
     from @t t 
     group by t.GROUP_KEY, t.MAIN_KEY 
    )a 
)b 
on b.GROUP_KEY = t.GROUP_KEY and b.MAIN_KEY = t.MAIN_KEY 
+0

感谢这真的很有帮助,是否有可能将此更改为更新查询?我试图理解你插入和声明的语法,因为我已经有了表并且想更新它。 thnx – moe

+0

它正在失败@t,所以这就是为什么我试图简化使用更新查询,因为我已经有了标志列表。 thnx – moe

+0

@moe,我已经更新了我的答案。而不是'@ t'使用你的表名。 –