我可以在SQL Server中使用逻辑来选择从哪个表生成视图吗?
我有一个表,称之为“逾期未还的账户”,我想创建一个视图,检查该表中是否有记录customerID。如果没有,我希望数据来自另一个表“Accounts” 比如说:我可以在SQL Server中使用逻辑来选择从哪个表生成视图吗?,sql,sql-server,sql-server-2008,tsql,Sql,Sql Server,Sql Server 2008,Tsql,我有一个表,称之为“逾期未还的账户”,我想创建一个视图,检查该表中是否有记录customerID。如果没有,我希望数据来自另一个表“Accounts” 比如说: IF customerID IS IN Overdue_Accounts THEN SELECT customerID, Overdue as Amt FROM Overdue_Accounts ELSE SELECT customerID, Balance as Amt FR
IF customerID IS IN Overdue_Accounts
THEN
SELECT customerID, Overdue as Amt
FROM Overdue_Accounts
ELSE
SELECT customerID, Balance as Amt
FROM Accounts
帐户将拥有每个客户ID
。以下是我正在寻找的示例:
账户:
customerID | Balance
001 | 100.00
002 | 200.00
003 | 300.00
004 | 400.00
005 | 500.00
逾期账款:
customerID | Overdue
003 | 5.00
customerID | Amt
001 | 100.00
002 | 200.00
003 | 5.00
004 | 400.00
005 | 500.00
结果:
customerID | Overdue
003 | 5.00
customerID | Amt
001 | 100.00
002 | 200.00
003 | 5.00
004 | 400.00
005 | 500.00
您可以使用
union all
和not exists()
:
rextester演示:
返回:
+------------+--------+
| customerID | Amt |
+------------+--------+
| 001 | 100.00 |
| 002 | 200.00 |
| 003 | 5.00 |
| 004 | 400.00 |
| 005 | 500.00 |
+------------+--------+
假设
customerID
在两个表中都是唯一的,您可以尝试
SELECT
a.customerID,
COALESCE(o.Overdue, a.Balance) AS Amt
FROM
Accounts a
LEFT OUTER JOIN
Overdue_Accounts o ON a.customerID = o.customerID
您可以将
合并
功能与左连接结合使用
:
SELECT
Accounts.customerID,
COALESCE(Overdue_Accounts.Overdue, Accounts.Balance) AS Amt,
FROM Accounts
LEFT JOIN Overdue_Accounts ON Overdue_Accounts.customerID = Accounts.customerID
左连接
确保我们尝试为每个帐户
获取一个过期的\u帐户
行
COALESCE
函数返回其第一个非空参数:
- 如果我们找到一个
行,那么过期的\u账户
不为空,我们返回它过期的\u账户。过期的
- 如果我们没有找到
行,我们将返回过期的\u账户
账户。余额