SQL Server如何编写查询,其中一个结果应具有第一个条件,其余条件是可选的

时间:2019-01-24 15:04:54

标签: sql-server

我想写一个查询,其中我的结果应包含至少一个第一个条件的结果,其余条件是可选的。

我在下面尝试类似的方法。

SELECT * FROM Student
WHERE Condition1
AND
(
Condition2
OR
Condition3
)

下面是我的样品

IF OBJECT_ID('tempdb..#Student') IS NOT NULL
    DROP TABLE #Student

CREATE TABLE #Student
(
    StudentID INT,
    IsActive BIT,
    IsPassed BIT,
    IsProjectDone BIT
)

INSERT INTO #Student
SELECT 1, 1, 1, 0
INSERT INTO #Student
SELECT 2, 0, 0, 1
INSERT INTO #Student
SELECT 3, 1, 1, 1
INSERT INTO #Student
SELECT 4, 0, 0, 0




SELECT * FROM #Student

-- SO I want atleast one record of Isactive =1  and other conditions such as (ispassed = 1, isprojectdone = 1 are optional

4 个答案:

答案 0 :(得分:0)

您可以有条件地这样做

Declare @Clientid int = 1
Select * from YourTable
where 
Col2 > 0  --(any true condition)
 or 
(isnull(col1,0) = @clientid or @Clientid is null)  --(any condition which may or may not true i.e parameter passed and it may be have proper value or null)


--Again run above query with clientid is null
Set @Clientid = null
Select * from YourTable
where 
Col2 > 0  --(any true condition)
 or 
(isnull(col1,0) = @clientid or @Clientid is null)

或者您可以使用Sqlserver的Exists功能

SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);

答案 1 :(得分:0)

您的问题是如何获得至少一条记录,其中Isactive = 1和其他条件(例如(Ispassed = 1,Isprojectdone = 1)是可选的)。

如果其他条件是可选的,那么为什么还要根据这些条件过滤数据。

您在所附评论中提出了建议:

  

所以在结果中我想查看ID为1,3的学生记录,因为   IsActive = 1,我也应该能够查看学生记录:2因为   IsProjectDone = 1

根据您的评论,条件没有其他选择,您需要让所有满足至少一项条件的学生

由于您的条件基于BIT类型的列,因此您可以这样做:

SELECT *
FROM #Student
WHERE IsActive | IsProjectDone | IsPassed = 1

答案 2 :(得分:0)

在“可选”下您是指“未指定”吗? 如果是这样,下面的脚本应该可以工作。声明但未指定@IsPassed和@IsProjectDone时,您将获得所有在职学生。如果指定这些参数,则将获得其他过滤。

DECLARE @IsPassed BIT
DECLARE @IsProjectDone BIT

-- SET @IsPassed = 1
-- SET @IsProjectDone = 1

SELECT * FROM #Student
WHERE IsActive = 1 AND 
    (@IsPassed IS NULL OR IsPassed = @IsPassed) AND
    (@IsProjectDone IS NULL OR IsProjectDone = @IsProjectDone)

答案 3 :(得分:-1)

SELECT TOP 1 * FROM Student
WHERE Condition1
UNION 
SELECT * FROM Student
WHERE Condition1
AND
(
   Condition2 OR Condition3 
)