跳过或添加条件,直到我得到行计数1作为结果

时间:2016-06-29 07:10:41

标签: sql-server common-table-expression

我正在寻找一些CTE或查询,我需要在获得1条记录的结果时停止执行/忽略where条件

CREATE TABLE EmployeeTest
(
    ID INT PRIMARY KEY IDENTITY(1,1)
    ,Name VARCHAR(100)
    ,City VARCHAR(100)
    ,Phone VARCHAR(100)
    ,ZipCode VARCHAR(20)
)


INSERT INTO EmployeeTest VALUES ('Venkat','Hyderabad','9849898401','500018')
INSERT INTO EmployeeTest VALUES ('Venkat','Hyderabad','9849898401','500019')
INSERT INTO EmployeeTest VALUES ('Venkat','Hyderabad','9849898402','500019')
INSERT INTO EmployeeTest VALUES ('Venkat','Secunderabad','9849898402','500019')
INSERT INTO EmployeeTest VALUES ('Name1','Secunderabad','9849898402','500019')

Ex: 1
--output is 1
select * from employeetest
where name = 'Venkat'
and city = 'hyderabad'
and phone='9849898401'
and zipcode='500018'

输出: 1 Venkat Hyderabad 9849898401 500018

Ex 2: 邮政编码为500020的结果。

select * from employeetest
where name = 'Venkat'
and city = 'hyderabad'
and phone='9849898401'
and zipcode='500020'

输出: 输出应该是1条记录,但我们需要忽略邮政编码,因为我们没有邮政编码500020的记录。

We have two records but i need first as output
1   Venkat  Hyderabad   9849898401  500018
2   Venkat  Hyderabad   9849898401  500019
Final Output would be,
1   Venkat  Hyderabad   9849898401  500018

我认为我们可以用CTE做到但无法实现。

目标是我们需要在where子句中应用每个条件,直到我们获得单个记录。如果我们为第一个条件获得更多记录[name =' Venkat']我们需要申请第二个[city =' hyderabad']等等......

任何想法!提前谢谢。

2 个答案:

答案 0 :(得分:3)

这样的事情应该有效:

DECLARE @city VARCHAR(100) = 'hyderabad'
DECLARE @name VARCHAR(100) = 'Venkat'
DECLARE @phone VARCHAR(100) = '9849898401'
DECLARE @zipcode VARCHAR(100) = '500020'

SELECT TOP 1 ID, Name, City, Phone, ZipCode, t.matches
FROM EmployeeTest 
CROSS APPLY (
   SELECT IIF(Name=@name, 1, 0) + IIF(City=@city, 1, 0) + 
          IIF(Phone=@phone, 1, 0) + IIF(ZipCode=@zipcode, 1, 0) AS matches) AS t
WHERE t.matches <> 0
ORDER BY t.matches DESC 

查询返回具有最多匹配数的单个记录。

答案 1 :(得分:0)

您不需要使用CTE。您可以使用以下查询仅显示1条记录。

select top 1 * from employeetest
where name = 'Venkat'

这只为您提供了one record with name of 'Venkat'