Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何改进SQL Server中的更新语句_Sql_Sql Server_Tsql - Fatal编程技术网

如何改进SQL Server中的更新语句

如何改进SQL Server中的更新语句,sql,sql-server,tsql,Sql,Sql Server,Tsql,我使用的是SQL Server,我有两个表,第一个叫做MCross 它有3列 Brand1 Brand2 Cnt -------------------- Mazda Toyota NULL Ford Toyota NULL Nissan Mazda NULL BMW Opel NULL Nissan BMW NULL 另一张表叫做Tags AgentID Brand Class ---------------------- 1

我使用的是SQL Server,我有两个表,第一个叫做MCross

它有3列

Brand1  Brand2  Cnt
--------------------
Mazda   Toyota  NULL
Ford    Toyota  NULL
Nissan  Mazda   NULL
BMW     Opel    NULL
Nissan  BMW     NULL
另一张表叫做Tags

AgentID  Brand     Class
----------------------
1        Toyota    C
1        Toyota    S
1        BMW       X7
1        BMW       X5 
1        BMW       X3
1        Mazda     3
2        Toyota    C
2        Toyota    S
2        Mazda     5
2        Mazda     3
3        BMW       X3
3        Nissan    P
4        Nissan    L
4        BMW       X3
我想用Brand1和Brand2的代理数量更新MCross

我试过这个

但是它非常慢,我认为可以用更好的方式来写

update A
    set Cnt = B.cnt
from MCross A
inner join (
    select C.Brand1, C.Brand2, count(T.AgentID) cnt
    from MCross C
    inner join (
        select AgentID, ','+STRING_AGG(cast(Brand as NVARCHAR(MAX)),',')+',' AS Brands
        from Tags
        group by AgentID
    ) T on T.Brands Like  '%,'+C.Brand1+',%' and T.Brands Like  '%,'+C.Brand2+',%' 
    group by C.Brand1, C.Brand2
) B on A.Brand1 = B.Brand1 and A.Brand2 = B.Brand2

看看这是否适合您:

编辑:

嗯。您可以使用应用程序:

注意:如果您想对数据中的所有品牌对进行此操作,只需使用自连接:

with a as (
      select distinct agentid, brand
      from tags
     )
select a1.brand, a2.brand, count(*)
from a a1 join
     a a2
     on a1.agentid = a2.agentid and
        a1.brand <> a2.brand
group by a1.brand, a2.brand;

我忘了提到同一品牌可以在同一家代理商重复使用检查新的。
update m
   set m.cnt = a.num_agents
   from mcross m outer apply
        (select count(*) as num_agents
         from (select t.agentid
               from tags t
               where t.brand in (m.brand1, m.brand2)
               group by t.agentid
               having count(distinct t.brand) = 2
              ) a
        ) a;
with a as (
      select distinct agentid, brand
      from tags
     )
select a1.brand, a2.brand, count(*)
from a a1 join
     a a2
     on a1.agentid = a2.agentid and
        a1.brand <> a2.brand
group by a1.brand, a2.brand;