我有2个表:Income
(InvoiceDate, TotalAmount
)和Outcome
(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出了什么问题?
谢谢! 蓬安
答案 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
function将NULL
替换为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
)