當沒有找到記錄時,我希望看到特定欄位回傳 0 值。以下是我迄今為止嘗試過的 SQL 查詢。
SELECT Customer, Address, Number of lines, Date
FROM table_name
WHERE Date = '30-5-2022' AND Customer IN (A, B, C)
它回傳的只有 1 行,如下所示。
| 顧客 | 地址 | 行數 | 日期 |
|---|---|---|---|
| 一個 | 3 | 射頻 | 30-5-2022 |
但我期望看到的是:
| 顧客 | 地址 | 行數 | 日期 |
|---|---|---|---|
| 一個 | 英國 | 33 | 30-5-2022 |
| 乙 | 0 | 0 | 30-5-2022 |
| C | 0 | 0 | 30-5-2022 |
客戶 B 和 C 在 2022 年 5 月 30 日沒有記錄,但我仍然需要查看行,但某些列可以為 0。請告知我是否遺漏了什么?非常感謝!
uj5u.com熱心網友回復:
試試下面的查詢:
SELECT A.Customer, ISNULL(B.Address, 0),
ISNULL(B.[Number of lines],0), ISNULL(B.Date, '30-05-2022') Date
FROM
(
SELECT DISTINCT Customer
FROM table_name
) A
LEFT JOIN table_name B
ON A.Customer = B.Customer
AND B.Date = '30-5-2022'
這將輸出表中存在的所有客戶。WHERE您可以根據您的要求在上述查詢末尾過濾帶有子句的客戶。
dbfiddle 鏈接
uj5u.com熱心網友回復:
假設客戶在一個表 (cust) 中,而其他東西在另一個表 (table_name) 中,并且他們與一個名為 custid 的 id 連接,您需要一些甜蜜的、甜蜜的左連接操作,例如:
SELECT c.Customer, c.Address, isnull([Number of lines],0), d.Date
FROM cust c left join table_name d on c.custid = d.custid and
d.Date = '30-5-2022' where
c.Customer IN ('A', 'B', 'C')
uj5u.com熱心網友回復:
您需要將 A、B、C 放在一個表中,然后將主表左連接到它。然后,所有其他條件都必須放在ON子句中,而不是WHERE.
您可以為此使用虛擬VALUES子句
SELECT Customer, Address, Number of lines, Date
FROM (VALUES
('A'),
('B'),
('C')
) v(Customer)
LEFT JOIN table_name tn ON tn.Customer = v.Customer
AND tn.Date = '30-5-2022';
或者,您可以傳入表值引數,或使用表變數。不要忘記添加主鍵。
DECLARE @tmp TABLE (Customer varchar(100) PRIMARY KEY);
INSERT @tmp(Customer) VALUES
('A'),
('B'),
('C');
SELECT Customer, Address, Number of lines, Date
FROM @tmp v
LEFT JOIN table_name tn ON tn.Customer = v.Customer
AND tn.Date = '30-5-2022';
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483415.html
