Multiple FULL OUTER JOIN on multiple tables

前端 未结 5 1839
暗喜
暗喜 2020-12-23 20:36

I have multiple outer joins

SELECT  A.column2
        , B.column2
        , C.column2
FROM 
(
    (SELECT month, column2 FROM table1) A
    FULL OUTER JOIN
          


        
相关标签:
5条回答
  • 2020-12-23 21:07

    I can think of 2 ways off the bat that you can address this, depending on what the actual logic is to define the results you want.

    The first, and most fool-proof way, is to use GROUP BY month, and use aggregate functions like MAX(column2) to get the non-zero rows only, or if there are multiple non-zero rows you want to add, use SUM(). This is the best solution if there is an aggregate function that fulfills your logical intent.

    Another is to include more conditions in your JOIN, like "WHERE a.month=b.month AND b.column2 > 0", but that still won't solve the problem if there can be more than one non-zero row.

    0 讨论(0)
  • 2020-12-23 21:10

    One of the ways to do this could be create "anchor" table from all possible data from all three tables and then use left outer join:

    select
        A.column2,
        B.column2,
        C.column2
    from (
        select distinct month from table1
        union
        select distinct month from table2
        union
        select distinct month from table3
    ) as X
        left outer join table1 as A on A.month = X.month
        left outer join table2 as B on B.month = X.month
        left outer join table3 as C on C.month = X.month
    
    0 讨论(0)
  • 2020-12-23 21:18
    SELECT  A.column2
            , B.column2
            , C.column2
    FROM 
    (
        (SELECT month, column2 FROM table1) A
        FULL OUTER JOIN
        (SELECT month, column2 FROM table2) B on A.month= B.month
        FULL OUTER JOIN 
        (SELECT month, column2 FROM table3) C on ISNULL(A.month, B.month) = C.month
    )
    
    0 讨论(0)
  • 2020-12-23 21:22

    Use option with COALESCE function to determine a column grouping.

    SELECT COALESCE(t1.Month, t2.Month, t3.Month) AS Month, 
           SUM(ISNULL(t1.Col1, 0)) AS t1Col1, 
           SUM(ISNULL(t2.Col1, 0)) AS t2Col1, 
           SUM(ISNULL(t3.Col1, 0)) AS t3Col1
    FROM dbo.table1 t1 FULL OUTER JOIN dbo.table2 t2 ON t1.Month = t2.Month
                       FULL OUTER JOIN dbo.table3 t3 ON t1.Month = t3.Month
    GROUP BY COALESCE(t1.Month, t2.Month, t3.Month)
    
    0 讨论(0)
  • 2020-12-23 21:24

    something like

    select month, sum(a) a,  sum(b) b, sum(c) c from (
      SELECT month, column2 A, 0 B, 0 C FROM table1 
        union 
      SELECT month, 0 A, column2 B, 0 C FROM table2
        union 
      SELECT month, 0 A, 0 B, column2 C FROM table3
    ) x
    group by month
    
    0 讨论(0)
提交回复
热议问题