1

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

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

这是我的桌子

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

我只知道如何进行正常的更新查询,但不知道从哪里开始这个逻辑。谢谢帮助

4

1 回答 1

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
于 2013-10-22T00:17:17.117 回答