添加Excels vlookup之类的列

时间:2017-12-13 11:47:08

标签: sql sql-server common-table-expression

我正在为下面的表添加列multi_company。一个告诉用户是否存在于两个或更多公司的人。我想出了一个工作片段,但一直认为必须有一个更好,更快的方法。

customer     company      size      multi_company
justine      google       1         1
jack         google       5         0
grace        google       4         1
justine      microsoft    2         1
grace        microsoft    3         1

性能是一个真正的问题,因为数据集很大,这个自动化过程应该每天都运行。任何人都可以想出一个更好的解决方法吗?

create table #1(customer varchar(255), company varchar(255), size int)
insert into #1(customer, company, size) values('justine', 'google', 1)
insert into #1(customer, company, size) values('jack', 'google', 5)
insert into #1(customer, company, size) values('grace', 'google', 4)
insert into #1(customer, company, size) values('justine', 'microsoft', 2)
insert into #1(customer, company, size) values('grace', 'microsoft', 3)
;
with cte as (
select customer
     , count(1) as multi_company 
  from #1 
 group by customer 
   having count(1) > 1
)
select #1.*
     , case when cte.multi_company is not null 
            then 1 
            else 0 end as multi_company 
  from #1 
  left join cte on #1.customer = cte.customer

2 个答案:

答案 0 :(得分:1)

我认为你几乎就在那里。你只需要简化一下:

CUSTOMER        COMPANY         MULTI_COMPANY
--------------- --------------- -------------
justine         microsoft                   1
justine         google                      1
grace           microsoft                   1
grace           google                      1
jack            google                      0

我得到了这个输出:

{{ Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $memoriesRow->createdAt, 'UTC')->setTimezone($timezone)->format('l, F dS Y h:i A') }}

答案 1 :(得分:0)

这会有帮助???

SELECT
  customer,
  company,
  size,
  CASE
    WHEN COUNT(customer) OVER (PARTITION BY customer ORDER BY customer) >1 THEN 1
    ELSE 0
  END AS multi_company
FROM cust