1

我有 2 个表:( Income)InvoiceDate, TotalAmountOutcome( ExpenseDate, 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 出了什么问题?

谢谢你!彭甘

4

2 回答 2

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)
于 2013-10-19T17:24:58.400 回答
0

CASE语句是一系列运算符的简写=。但是,NULL永远等于任何值(这就是IS运算符的用途),因此CASE用于评估NULLs 有点毫无意义。

相反,您可以使用以下COALESCE功能将您NULL的 s 替换为 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
)
于 2013-10-19T17:25:50.130 回答