对不起,我知道这应该相对简单,可能以前已经回答过了,但我在这方面被屏蔽了,在这里找不到匹配的帖子。
我有两张桌子公司和联系人。一个联系人可以链接到0或1个公司,一个公司可以有1个或多个联系人,并且可能有一个设置为"主要联系人">
公司(ccyID、ccyname、primconID(
________________________________________________
| ccyID | ccyname | PrimconID |
------------------------------------------------
| aaaaaaa | Company A | NULL |
| bbbbbbb | Company B | NULL |
| ccccccc | Company C | vvvvvvv |
________________________________________________
联系人(conID、firstname、lastname、ccyID(
__________________________________________________
| conID | first | last | companyID |
--------------------------------------------------
| zzzzzzz | Stand | Alone | NULL |
| yyyyyyy | Only | Contact | aaaaaaa |
| xxxxxxx | CompanyB | First | bbbbbbb |
| wwwwwww | CompanyB | Second | bbbbbbb |
| vvvvvvv | CompanyC | Only | ccccccc |
_________________________________________________
我需要一个SELECT,当公司只有一个联系人时,它将返回companyID和contactID,并且没有PrimconID集,即对于上述数据,我希望返回
conID ccyID
----------------
yyyyyyy aaaaaaa
(最终的想法是,我将更新表格,使公司的单独联系人成为主要联系人(
按公司分组联系人,只保留计数为1的联系人,并确保他们在没有主要联系人的公司中:
select companyid, max(conid)
from contacts
group by companyid
having count(*) = 1
and companyid in (select ccyid from companies where primconid is null)
order by companyid;
我会使用join
和group by
:
select c.ccyid, max(co.conid)
from companies c join
contacts co
on co.companyid = c.ccyid
where c.PrimconID is null
group by c.ccyid
having min(co.conID) = max(co.conID);
作为update
语句,您可以执行以下操作:
update c
set PrimconID = co.conid
from companies c join
(select co.companyid, max(co.conid) as conid
from contacts co
group by companyid
having min(co.conid) = max(co.conid)
) co
on co.companyid = c.ccyid
where c.PrimconID is null ;
使用CTE首先识别只有一个公司的所有联系人,然后加入公司表:
WITH cte AS (
SELECT ccyID, MAX(conID) AS conID
FROM contacts
GROUP BY ccyID
HAVING COUNT(*) = 1
)
SELECT
t.conID,
c.ccyID
FROM companies c
INNER JOIN cte t
ON c.ccyID = t.ccyID
WHERE
c.PrimconID IS NULL;
请参阅下面的演示以查看查询的工作情况。