如何在TSQL中选择更具体的值 [英] How do select a more specific value in TSQL

查看:67
本文介绍了如何在TSQL中选择更具体的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个存储一堆默认值的表,其中可能会覆盖这些值。如果没有找到特定的,我需要一个查询来选择默认值。



在下面的示例中,如果F2为null,则F1为默认值。如果F2不为null,我想返回它。



所以我可以通过首先查看是否存在特定行来解决这个问题,然后选择那些行,否则选择默认值行。它只是感觉很笨重和重复。是否可以在一个查询中包含所有内容?



我尝试过:



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:

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

*/

推荐答案

如果你的表名为't_example',你可以使用这个选择:
If your table is named 't_example' you could use this select stament:
SELECT  f1,MAX(F2) AS F2
	FROM t_example
	GROUP  BY F1
	ORDER BY 1



这会产生以下结果:

F1 F2

A 1

B 2

C NULL



如果你想要你可以添加'where'之类的:


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

If you want you can add a 'where' like:

SELECT  f1,MAX(F2) AS F2
	FROM t_example
	WHERE F1='B'
	GROUP  BY F1


这篇关于如何在TSQL中选择更具体的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆