在SQL中使用Condition更新查询

时间:2013-10-21 23:41:10

标签: sql sql-server tsql

我有一个包含2列的表,我正在尝试根据这些条件更新另一个表:

  1. 为同一GROUP_KEY的Main_Key列中的大多数重复键设置标记为'Good'(注意我们可以为任何GROUP_KEY设置不同的Main_Key)
  2. 为同一GROUP_KEY的Main_Key列中的最少重复键设置标记为“Bad”
  3. 如果同一GROUP_KEY的不同Main_Keys相等,则将标志设置为“不使用”
  4. 这是我的表

    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
    

    此处是更新后的理想结果

    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的帮助

1 个答案:

答案 0 :(得分: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