'SQL Query, If column1 is null then use the value from column2, else column1
I want to select from one table with the condition, if column1 is null then use the value from column2, and if column2 is null then use the value from column1.
This is my table structure:
CREATE TABLE [dbo].[R_Warehouse]
(
[InvID] [char](15) NOT NULL,
[DivNo] [tinyint] NOT NULL,
[InvDate] [datetime] NOT NULL,
[RefNo2] [varchar](20) NULL,
CONSTRAINT [PK_R_Warehouse_1]
PRIMARY KEY CLUSTERED ([InvID] ASC, [DivNo] ASC, [InvDate] ASC)
)
INSERT INTO R_Warehouse(InvID, DivNo, InvDate, RefNo2)
VALUES
('211130042R9645', '1','2022-01-30', 'UL13Z01Y83')
, ('211130042R9645', '1','2022-01-31', 'UL13Z01Y83')
, ('211130042R9645', '1','2022-02-01', 'UL13Z01Y83')
, ('211130042R9645', '1','2022-04-29', 'UL13Z01Y83')
, ('Y22012800880', '1','2022-01-30', '')
, ('Y22012800880', '1','2022-01-31', '')
, ('Y22012800880', '1','2022-02-01', '')
, ('Y22012800880', '1','2022-04-29', '')
, ('M19030102750', '1','2022-01-30', '')
, ('M19030102750', '1','2022-01-31', '')
, ('M19030102750', '1','2022-02-01', '')
, ('M19030102750', '1','2022-04-29', '')
, ('Z22011800090', '1','2022-01-30', '')
, ('Z22011800090', '1','2022-01-31', '')
, ('Z22011800090', '1','2022-02-01', '')
, ('Z22011800090', '1','2022-04-29', '')
I tried to create this query
SELECT InvID, RefNo2, InvDate
FROM R_Warehouse
WHERE InvDate = '2022-02-01'
AND InvID = '211130042R9645'
UNION
SELECT InvID, RefNo2, InvDate
FROM R_Warehouse
WHERE InvDate = '2022-02-01'
AND RefNo2 = 'UL13Z01Y83'
This will produce the following output;
+----------------+---------------+-----------+
| InvID | RefNo2 | InvDate |
+----------------+---------------+-----------+
| 211130042R9645 | UL13Z01Y83 | 2022-02-01|
+----------------+---------------+-----------+
And it's running well.
I tried to remove the condition of InvID = ''. This will produce the following output;
+----------------+---------------+-----------+
| InvID | RefNo2 | InvDate |
+----------------+---------------+-----------+
| 211130042R9645 | UL13Z01Y83 | 2022-02-01|
+----------------+---------------+-----------+
And it's running well also.
But when I remove the condition of RefNo2 = ''. This will produce the following output;
+----------------+---------------+-----------+
| InvID | RefNo2 | InvDate |
+----------------+---------------+-----------+
| 211130042R9645 | | 2022-02-01|
| Y22012800880 | | 2022-02-01|
| M19030102750 | | 2022-02-01|
| Z22011800090 | | 2022-02-01|
| M22020103DF0 | | 2022-02-01|
+----------------+---------------+-----------+
Why does the result come out so much. In my table structre (1) InvID = (M) RefNo2.
I have tried using other methods like CASE WHEN, COALESCE, UNION but the return are still the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
