当结果仅匹配 1 db 的参数时从 3 dbs 获取查询结果

Getting query results from 3 dbs when result only matches parameters of 1 db

假设我有 3 家公司都有客户。我想编写一个代码,在所有 3 家公司中搜索已被终止和解雇的客户,然后 return 搜索该人作为客户的所有公司,而不管这些公司的客户状态如何。

我拥有的最佳代码是:

SELECT
x.name,
x.social,
  CASE
  when (SUM(x.company) = 1) then ('A')
  when (SUM(x.company) = 2) then ('B')
  when (SUM(x.company) = 4) then ('C')
  when (SUM(x.company) = 3) then ('A + B')
  when (SUM(x.company) = 5) then ('A + C')
  when (SUM(x.company) = 6) then ('B + C')
  when (SUM(x.company) = 7) then ('X')
  else NULL end AS company

FROM
(SELECT 
a.name as name, 
a.socsec, 
("1") AS company
FROM
 a
WHERE
  (a.status = 'Active') AND 
  ((a.trans IN ('Payroll','HR')) AND 
  (a.result IN ('Terminated','LaidOff')) 
GROUP BY
  a.socsec

UNION

SELECT 
b.name as name, 
b.socsec, 
("2") AS company
FROM
 b
WHERE
  (b.status = 'Active') AND 
  ((b.trans IN ('Payroll','HR')) AND 
  (b.result IN ('Terminated','LaidOff')) 
GROUP BY
  b.socsec

UNION

SELECT 
c.name as name, 
c.socsec, 
("4") AS company
FROM
 c
WHERE
  (c.status = 'Active') AND 
  ((c.trans IN ('Payroll','HR')) AND 
  (c.result IN ('Terminated','LaidOff'))
GROUP BY
  c.socsec) idx

GROUP BY
 x.socsec
ORDER BY
 company

此代码只有 returns 个满足终止过滤器的客户帐户,所以如果我有一个客户在公司 A 中有一个终止代码但在 B 中有一个正常帐户,它只有 returns她在 A 有一个账户。 我喜欢 return 'A+B' 该客户,因此只要任何一个客户帐户符合过滤器,它就应该 return 该客户拥有帐户的所有公司。

我能想到的最佳解决方案是联合所有 3 家公司之间的所有帐户,然后在 UNION 之外的 OR 语句中应用过滤器,但这需要很长时间才能 运行 它冻结而且我什至没有当然可以。

有什么想法吗?

我原以为这可行,但它需要很长时间才能冻结,这是我的系统无法处理的有效解决方案吗?

SELECT
x.name,
x.social,
 CASE
  when (SUM(x.company) = 1) then ('A')
  when (SUM(x.company) = 2) then ('B')
  when (SUM(x.company) = 4) then ('C')
  when (SUM(x.company) = 3) then ('A + B')
  when (SUM(x.company) = 5) then ('A + C')
  when (SUM(x.company) = 6) then ('B + C')
  when (SUM(x.company) = 7) then ('X')
  else NULL end AS co

FROM
(
  SELECT 
   a.name, 
   a.social, 
   ("1") AS company
   FROM a

UNION

  SELECT 
   b.name, 
   b.social, 
   ("2") AS company
   FROM b

UNION

  SELECT 
   c.name, 
   c.social, 
   ("4") AS company
   FROM c
) idx

LEFT OUTER JOIN a ON a.social = x.social
LEFT OUTER JOIN b ON b.socsec = x.socsec
LEFT OUTER JOIN c ON c.socsec = x.socsec

WHERE
((a.status = 'Active') AND 
(a.balance > 0.00) AND 
(a.trans IN ('Payroll','HR')) AND 
(a.result IN ('Terminated','LaidOff')))
OR
((b.status = 'Active') AND 
(b.balance > 0.00) AND 
(b.trans IN ('Payroll','HR')) AND 
(b.result IN ('Terminated','LaidOff')))
OR
((c.status = 'Active') AND 
(c.balance > 0.00) AND 
(c.trans IN ('Payroll','HR')) AND 
(c.result IN ('Terminated','LaidOff')))

GROUP BY x.social
ORDER BY co