2014-06-24 62 views
0

SQL引擎:MSSQL如何避免笛卡爾乘積當我們總結(從DIF兩種不同的列表)

目標:合併兩個不同的總和

這是我的查詢:

SELECT z.zlec_id AS zlec, 
     ( 
     CASE WHEN Sum(netto_blind_discout * p.count) IS NOT NULL 
     THEN 
      Sum(netto_blind_discout * p.count) 
     ELSE 
      0 
     END 
     + 
     CASE WHEN Sum(netto2 * d.count) IS NOT NULL 
     THEN 
      Sum(netto2 * d.count) 
     ELSE 
      0 
     END 
     ) AS res, 
     Sum(netto_blind_discout * p.count), 
     Sum(netto2 * d.count) 
FROM zetter z 
     FULL OUTER JOIN 
     (
         SELECT netto_blind_discout, 
           count, 
           zlec_id 
         FROM position 
    ) AS p 
     ON z.zlec_id = p.zlec_id 

     FULL OUTER JOIN 
     (
         SELECT netto2, 
           count, 
           zlec_id 
         FROM d_additional 
    ) AS d 
     ON z.zlec_id = d.zlec_id 

WHERE z.zlec_id = 123123 
GROUP BY z.zlec_id 

如何避免笛卡爾產品第一次加入和第二次? 它的產生,我奇怪的結果:

最終的結果是

(SUM of product * number_of_rows in d_additional) + (SUM of d_additional * number_of_rows in product), (SUM of product * number_of_rows in d_additional), (SUM of d_additional * number_of_rows in product)

哪裏是我的錯嗎?

+1

我用隨機SQL格式來格式化您的查詢。它仍然是可怕的,但比你發佈時還要少... – Sebas

+0

@Sebas,修正了語法sql-a –

回答

0

解決方案:

(從根到孩子和移動組)

SELECT z.zlec_id AS zlec, 
    ( 
    CASE WHEN sum_p IS NOT NULL 
    THEN 
     sum_p 
    ELSE 
     0 
    END 
    + 
    CASE WHEN sum_d IS NOT NULL 
    THEN 
     sum_d 
    ELSE 
     0 
    END 
    ) AS res, 
    sum_p, 
    sum_d 
    FROM zetter z, 
    ( 

        SELECT sum(netto_blind_discout * count) as sum_p, 
          p.zlec_id 
        FROM zetter z 
        Left join position p 
        on z.zlec_id = p.zlec_id 
        Group by p.zlec_id 
) AS p, 
    (
        SELECT sum(netto2 * count) as sum_d, 
          d.zlec_id 
        FROM zetter z 
        Left join d_additional d 
        on z.zlec_id = d.zlec_id 
        Group by d.zlec_id 
) AS d 
    WHERE 
     z.zlec_id = 123123 And 
     d.zlec_id = z.zlec_id and 
     p.zlec_id = z.zlec_id