2016-05-06 6 views
0

J'ai 3 table, je veux obtenir des données à partir de ces tables en utilisant join. Voici ma structure de table et mes données dans ces 3 tableaux. J'utilise MS Sql server.Obtenir des données à partir de table mutile dans le serveur SQL

enter image description here

Year Month  TotalNewCaseAmount TotalNewCaseCount TotalClosingAmount TotalReturnCount TotalClosingAmount TotalReturnCount 

2016 Januray  146825.91   1973    54774.41    147     299.35    41 

2016 Fabuary  129453.30   5384    46443.99    7     7568.21    123 

2016 March  21412.07   3198    Null     Null    78.83    73 

2016 April  0.00    5     Null     Null    Null    NULL 

Je ne sais pas ce qui me join ce résultat, je l'ai essayé CROSS JOIN, mais il me donner 36 suite.

+0

Essayez LEFT JOIN, pas CROSS JOIN –

Répondre

0

Cela fera:

;WITH Table1 AS (
SELECT * 
FROM (VALUES 
(2016, 'Januray', 146825.91, 1973), 
(2016, 'Fabuary', 129453.30, 5384), 
(2016, 'March', 21412.07, 3198), 
(2016, 'April', 0.00, 5) 
) as t ([Year], [Month], TotalNewCaseAmount, TotalNewCaseCount) 
), Table2 AS (
SELECT * 
FROM (VALUES 
(2016, 'Januray', 54774.41, 147), 
(2016, 'Fabuary', 46443.99, 7) 
) as t ([Year], [Month], TotalClosingAmount, TotalClosingCount) 
), Table3 AS (
SELECT * 
FROM (VALUES 
(2016, 'Januray', 299.35, 41), 
(2016, 'Fabuary', 7568.21, 123), 
(2016, 'March', 78.83, 73) 
) as t ([Year], [Month], TotalReturnAmount, TotalReturnCount) 
) 

SELECT t1.[Year], 
     t1.[Month], 
     t1.TotalNewCaseAmount, 
     t1.TotalNewCaseCount, 
     t2.TotalClosingAmount, 
     t2.TotalClosingCount, 
     t3.TotalReturnAmount, 
     t3.TotalReturnCount 
FROM table1 t1 
LEFT JOIN table2 t2 
    ON t1.[Year] = t2.[Year] AND t1.[Month] = t2.[Month] 
LEFT JOIN table3 t3 
    ON t1.[Year] = t3.[Year] AND t1.[Month] = t3.[Month] 

Sortie:

Year Month TotalNewCaseAmount TotalNewCaseCount TotalClosingAmount TotalClosingCount TotalReturnAmount TotalReturnCount 
2016 Januray 146825.91   1973    54774.41   147     299.35    41 
2016 Fabuary 129453.30   5384    46443.99   7     7568.21    123 
2016 March 21412.07   3198    NULL    NULL    78.83    73 
2016 April 0.00    5     NULL    NULL    NULL    NULL 

Il suffit de changer table1, table2 et table3 pour les noms de vos tables.

0

Essayez comme ça,

select 
t1.*, 
t2.TotalClosingAmount, 
t2.TotalClosingCount, 
t3.TotalRetrunAmount, 
t3.TotalReturnCount 
from 
Table1 t1 
left join 
Table2 t2 on t1.year=t2.year 
and t1.month=t2.month 
left join 
Table3 t3 on t1.year=t3.year 
and t1.month=t3.month 
0

S'il vous plaît essayer

select year,month, totalnewcasesamount,totalnewcasescount, 
    totalclosingamount,totalclosingcount,totlareturnamopunt,totalreturncount 

    from table1 full outer join 
    table2 
    on table1.year=table2.year 
    and table1.month=table2.month  
    full outer join table3 
    on table1.year=table3.year 
    and table1.month=table3.month 
    where table1.year is not null 
    and table1.month is not nulll