2017-05-10 13 views
2

テーブルがあり、それを "Overdue_Accounts"と呼んでいます。テーブルにcustomerIDというレコードがあるかどうかを確認するビューを作成したいとします。そうでない場合は、別のテーブル「勘定」からデータを取得します。ロジックを使用して、SQL Serverからビューを作成するテーブルを選択できますか?

ので、何かのように:

IF customerID IS IN Overdue_Accounts 
    THEN 
     SELECT customerID, Overdue as Amt 
     FROM Overdue_Accounts 
ELSE 
    SELECT customerID, Balance as Amt 
    FROM Accounts 

アカウントは、すべてのcustomerIDを持っているでしょう。

アカウント

customerID | Balance 
001  | 100.00 
002  | 200.00 
003  | 300.00 
004  | 400.00 
005  | 500.00 

Overdue_Accounts

customerID | Overdue 
003  | 5.00 

結果

customerID | Amt 
001  | 100.00 
002  | 200.00 
003  | 5.00 
004  | 400.00 
005  | 500.00 

答えて

1
ここで私が探しているもののサンプルです

あなたがunion allnot exists()使用することができます

SELECT customerID, Overdue as Amt 
FROM Overdue_Accounts 
union all 
SELECT customerID, Balance as Amt 
FROM Accounts a 
where not exists (
    select 1 
    from Overdue_Accounts o 
    where o.customerId = a.customerid 
) 
order by customerid 

rextesterデモ:http://rextester.com/QLSLP99762

戻っ:customerIDは、両方のテーブル内で一意であると仮定すると、

+------------+--------+ 
| customerID | Amt | 
+------------+--------+ 
|  001 | 100.00 | 
|  002 | 200.00 | 
|  003 | 5.00 | 
|  004 | 400.00 | 
|  005 | 500.00 | 
+------------+--------+ 
+0

ちょうど私が必要としていたデータで試しました。ありがとうございました。 –

+0

@PatrickSchomburgお手伝いをしますように! – SqlZim

0

を、あなたは試すことができます

SELECT 
    a.customerID, 
    COALESCE(o.Overdue, a.Balance) AS Amt 
FROM 
    Accounts a 
LEFT OUTER JOIN 
    Overdue_Accounts o ON a.customerID = o.customerID 
1

Y OUはLEFT JOINとの組み合わせでCOALESCE機能を使用することができます。

SELECT 
    Accounts.customerID, 
    COALESCE(Overdue_Accounts.Overdue, Accounts.Balance) AS Amt, 
FROM Accounts 
LEFT JOIN Overdue_Accounts ON Overdue_Accounts.customerID = Accounts.customerID 

LEFT JOINたちは、各AccountためOverdue_Accounts行を取得しようと保証します。

COALESCE関数はnullでその引数の最初のを返します。

  • 我々はOverdue_Accounts行を見つけた場合は、Overdue_Accounts.Overdueがnullでなく、我々はそれを返します。
  • Overdue_Accounts行が見つかりません代わりにAccounts.Balanceを返します。
関連する問題