Sql server 返回“默认”记录集的SQL查询
我需要一个处理默认记录集概念的查询 如果在运行查询时未找到请求的记录,则需要获取一组默认数据 以下是一个例子:Sql server 返回“默认”记录集的SQL查询,sql-server,Sql Server,我需要一个处理默认记录集概念的查询 如果在运行查询时未找到请求的记录,则需要获取一组默认数据 以下是一个例子: Rec Category Location -- -------- -------- 1 Attendee 0 2 Distributor 0 3 Sponsor 0 4 Attendee 1 5 Distributor 1 6 Sponsor
Rec Category Location
-- -------- --------
1 Attendee 0
2 Distributor 0
3 Sponsor 0
4 Attendee 1
5 Distributor 1
6 Sponsor 1
7 Attendee 2
8 Distributor 2
9 Sponsor 2
在案例1中,匹配请求的记录,例如从类别中选择*,其中位置=1。这显然会返回记录4、5和6
在案例2中,查询不匹配表中的任何记录,因此我希望使用默认记录;在本例中,我希望记录1、2和3作为默认记录。从类别中选择*,其中Location=5将找不到任何内容,因此应返回这些默认记录
我如何做到这一点?因为请求的记录不清楚。我以简单的方法结束。请检查下面的查询
Select * from (
select * from Category Where Location = 1
) t Where <Expression> = <Something>
union
select * from (
select * from Category where Location = 5
) t2 Where <Expression> != <Something>
如果您请求的记录部分是另一个select语句,则可以使用该语句
Select * from (
select * from Category Where Location = 1
) t Where Exists (Select 1 from tablex WHERE <Expression> = <Something> )
union
select * from (
select * from Category where Location = 5
) t2 Where NOT Exists (Select 1 from tablex WHERE <Expression> = <Something> )
谢谢你,西蒙娜。
我想通过一个简单的选择来处理这个问题,而您的解决方案正是我所需要的。我发布了一个新的答案,因为我不知道如何在回复中格式化代码
1当记录存在于location=1这样的位置时,我需要这些记录
2当某个位置的记录不存在时,我需要默认记录,即位置=0处的记录
-- Records for the location exists, return them
select * from Category Where Location = 1
union
select * from Category Where Location = 0 and not exists
(select * from Category Where Location = 1)
-- Records for the location do not exists, return the default records (location=0)
select * from Category Where Location = 7
union
select * from Category Where Location = 0 and not exists
(select * from Category Where Location = 7)
请求的记录是什么?是否希望在查询中使用此项,是否可以使用变量检查无数据?我不理解此部分,请从tablex中选择1,其中=但我想我理解此概念。您的doing two选择unioned,并且如果重新查询的记录不存在,您将只在union的一个部分中引入默认记录。明天我有时间解决这个问题,但我想我明白了!通过请求记录,我的意思很简单,我想做一个selct,如果没有记录匹配where location=1,那么select将返回where location=0的记录