2016-11-02 72 views
0

假設我有3家公司都有客戶。我想編寫一個代碼,搜索所有3家公司中已被終止和解僱的客戶,然後返回該客戶所屬的所有公司,而不管該客戶與這些公司的狀態如何。當結果僅匹配1db的參數時,從3dbs獲取查詢結果

最好的代碼,我有是:

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 

此代碼只返回滿足終止過濾器,所以如果我有在A公司終止的代碼,但在B中的正常賬戶的客戶的客戶賬戶,它只返回她有一個帳戶與A。 我喜歡它爲該客戶返回'A + B',所以只要任何一個客戶帳戶符合過濾器,它應該返回客戶有帳戶的所有公司。

我能想到的最好的解決方案是UNIONing所有3家公司之間的所有賬戶,然後在UNION之外的OR語句中應用過濾器,但需要這麼長時間才能運行它凍結,我甚至不知道它會工作。

有什麼想法?

回答

0

我在想這可能會工作,但它需要很長時間凍結,這是否是我的系統無法處理的工作解決方案?

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 
+0

對於任何人想知道,這確實是一個工作的解決方案 –