我对以下查询下表有疑问
1 | 0 |
2 | 0 |
3 | 101 |
4 | 102 |
5 | 201 |
1 | 201 |
每日协议表 -
101 | closed |
102 | open |
月度协议表 -
201 | closed |
202 | open |
我想创建一个查询来选择协议号和协议状态
的发票请帮助
答案 0 :(得分:0)
您可以使用左连接实现此目的。用你的替换这些表和列别名,这将是代码:
SELECT
InvoiceNo
, A.AgreementNo
, [AgreementStatus] = IFNull(B.AgreementStatus, C.AgreementStatus)
FROM
Agreements AS A
LEFT JOIN
DailyAgreements AS B
ON A.AgreementNo = B.AgreementNo
LEFT JOIN
MonthlyAgreements AS C
ON A.AgreementNo = C.AgreementNo
答案 1 :(得分:0)
使用LEFT JOIN
加入状态表,并使用CASE
检查每月或每日状态表是否已加入:
SELECT
i.invoice_no
, i.agreement_no
, CASE WHEN da.agreement_status IS NULL THEN ma.agreement_status ELSE da.agreement_status END as agreement_status
FROM invoice as i
LEFT JOIN daily_agreement as da ON da.agreement_no = i.agreement_no
LEFT JOIN monthly_agreement as ma ON ma.agreement_no = i.agreement_no
修改强>
我的查询应该返回如下行:
invoice_no | agreement_no| agreement_status
1 | 0 | null
2 | 0 | null
3 | 101 | closed
4 | 102 | open
5 | 201 | closed
1 | 201 | closed