无法将Income表和Outcome表与完全外连接合并

时间:2013-10-19 17:15:38

标签: sql sql-server tsql full-outer-join

我有2个表:IncomeInvoiceDate, TotalAmount)和OutcomeExpenseDate, TotalAmount)。

假设我有每列的数据如下:

Income

| INVOICEDATE | TOTALAMOUNT |
|-------------|-------------|
|  2013-10-16 |       22000 |
|  2013-10-17 |       14400 |
|  2013-10-18 |        4488 |

Outcome

| EXPENSEDATE | TOTALAMOUNT |
|-------------|-------------|
|  2013-10-25 |          15 |

我想合并这两个表来显示如下:

|       DATE | INCOME | OUTCOME |
|------------|--------|---------|
| 2013-10-25 |      0 |      15 |
| 2013-10-16 |  22000 |       0 |
| 2013-10-17 |  14400 |       0 |
| 2013-10-18 |   4488 |       0 |

然而,当我运行我的T-SQL时,它会显示如下:

|       DATE | INCOME | OUTCOME |
|------------|--------|---------|
|     (null) | (null) |      15 |
| 2013-10-16 |  22000 |  (null) |
| 2013-10-17 |  14400 |  (null) |
| 2013-10-18 |   4488 |  (null) |

这是我的T-SQL:

SELECT
    CASE (income.InvoiceDate)
       WHEN NULL THEN Outcome.expenseDate
       ELSE income.InvoiceDate
    END AS [Date],
    CASE (income.TotalAmount)
       WHEN NULL THEN 0
       ELSE income.TotalAmount
    END AS Income,
    CASE (Outcome.TotalAmount)
        WHEN NULL THEN 0
        ELSE Outcome.TotalAmount
    END AS Outcome
FROM
    Outcome
FULL OUTER JOIN 
    income ON Outcome.expenseDate = income.InvoiceDate
WHERE
    NOT (
        Outcome.TotalAmount = 0
        AND income.TotalAmount = 0
    )

您可以在http://sqlfiddle.com/#!6/3589f/1

测试此SQL

有谁知道我的T-SQL出了什么问题?

谢谢! 蓬安

2 个答案:

答案 0 :(得分:0)

您可能需要union代替

select InvoiceDate as Date, TotalAmount as Income, 0 as Outcome from Income
union all
select ExpenseDate, 0, TotalAmount from Outcome

如果您可以在同一天获得收入和支出,您可以将其分组。

select [date], Sum(Income), Sum(outcome) from
(
    select InvoiceDate as Date, TotalAmount as Income, 0 as Outcome from Income
    union all
    select ExpenseDate, 0, TotalAmount from Outcome
) v
group by [date]

关于你的陈述有什么问题,问题在于case。 他们应该使用is null而不是when null

CASE WHEN income.TotalAmount IS NULL THEN 0 ELSE income.TotalAmount end,

但更简短的方法是使用ISNULL

ISNULL(income.TotalAmount, 0)

答案 1 :(得分:0)

CASE语句是一系列=运算符的简写。但是,NULL 从不等于任何值(这是IS运算符的用途),因此使用CASE来评估NULL s是有点无意义。

相反,您可以使用COALESCE functionNULL替换为0,如下所示:

SELECT Outcome.expenseDate AS [Date],
       COALESCE(Income.TotalAMount, 0) AS Income,
       COALESCE(Outcome.TotalAMount, 0) AS Outcome
FROM   Outcome
FULL OUTER JOIN income ON Outcome.expenseDate = income.InvoiceDate
WHERE   NOT (
    Outcome.TotalAmount = 0
    AND income.TotalAmount = 0
)