Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I have a table storing a bunch of default values, where those values could be potentially overridden. I need a query to select the default value if no specific has been found.

In the example below, F1 is a default value if F2 is null. If F2 is not null, I want to return that instead.

So I can solve this by first seeing if specific rows exist, then selecting those rows otherwise selecting the default rows. It just feels really clunky and repetitive. Is way to include this all in a single query?

What I have tried:

SQL
DECLARE @x char = 'A'

DECLARE @t TABLE (
	F1 char,
	F2 int null
)

INSERT INTO @t (F1, F2) VALUES ('A', 1)
INSERT INTO @t (F1, F2) VALUES ('A', NULL)
INSERT INTO @t (F1, F2) VALUES ('B', 2)
INSERT INTO @t (F1, F2) VALUES ('C', NULL)

IF EXISTS(
			SELECT * 
			FROM @t
			WHERE F1 = @x AND
				F2 IS NOT NULL  
		)
BEGIN
	SELECT * 
	FROM @t
	WHERE F1 = @x AND
		F2 IS NOT NULL  
END 
ELSE
BEGIN
	SELECT * 
	FROM @t
	WHERE F1 = @x AND
		F2 IS NULL  
END

/*
This correctly returns 

when @x = 'A'
F1 F2
-------
A 1

when @x = 'B'
F1 F2
-------
B 2

when @x = 'C'
F1 F2
-------
C NULL

*/
Posted
Updated 19-Aug-18 21:17pm
Comments
[no name] 17-Aug-18 13:51pm    
F1 is a default value if F2 is null

Makes no sense.

1 solution

If your table is named 't_example' you could use this select stament:
SQL
SELECT  f1,MAX(F2) AS F2
	FROM t_example
	GROUP  BY F1
	ORDER BY 1

This produces the following result:
F1 F2
A 1
B 2
C NULL

If you want you can add a 'where' like:
SQL
SELECT  f1,MAX(F2) AS F2
	FROM t_example
	WHERE F1='B'
	GROUP  BY F1
 
Share this answer
 
Comments
CHill60 20-Aug-18 4:21am    
Good solution. The only thing I would add would be to explain why this works ... "Except for COUNT, aggregate functions ignore null values." See Aggregate Functions (Transact-SQL) | Microsoft Docs[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900