首先连接两列并计算组合的唯一出现次数,并用产品更新一列

First concat two columns and count the unique occurrences of the combinations, and update a column with the product

我有这个工作查询:

SELECT  jobtitle
       ,department
       ,COUNT({ fn CONCAT(jobtitle, department) }) AS occurrences
FROM mytable
GROUP BY jobtitle
        ,department

但现在我想通过更新 intnumber 来更新相同 table 的所有记录,并使用 occurrences 的值填充它] 在 jobtitle 和 department 值匹配的查询中创建的变量。

查询工作用了大约半天时间。但这有点太复杂了。 希望有人能帮忙

亲切的问候,

弗兰斯

您的 concat() 表达式与 count(*) 基本相同(只要两个值都不为空。)

with data as (
    select *, count(*) over (partition by jobtitle, department) as cnt
    from T
)
update data set num = cnt;

另请注意,成对的串联字符串可能会在组件不相等的情况下产生相同的值。例如,"A" + "BC" 等同于 "AB" + "C"。在你的情况下,我怀疑这会发生,但这是不必要的复杂性。

您可以在此处查看实际效果:https://rextester.com/CEVRX27211

您需要在更新语句中加入 table 和您的查询:

update m
set m.number = t.occurrences
from mytable m inner join (
  select jobtitle, department,
    count(concat(jobtitle, department)) as occurrences
  from mytable
  group by jobtitle, department
) t on t.jobtitle = m.jobtitle and t.department = m.department

但我相信您也可以使用 count(*) 而不是 count(concat(jobtitle, department))