检查列的所有值

时间:2015-06-10 11:32:40

标签: sql-server

选择所有具有偶数卷号的学生

Dept No     Roll No   Student Name 

 1         1          lee 
 1         2          scott
 2         2          scott
 2         4          smith
 1         4          smith

这应该导致DEpt no 2,因为它只有滚动数可被2整除的学生

3 个答案:

答案 0 :(得分:2)

另一种(imo简单轻量级)方式是使用NOT EXISTSDISTINCT

SELECT DISTINCT [Dept No]
FROM dbo.TableName t
WHERE NOT EXISTS
(
    SELECT 1 FROM dbo.TableName t2
    WHERE t.[Dept No] = t2.[Dept No]
      AND t2.[Roll No] % 2 = 1
)

Demo

如果没有奇数,则必须均匀。

答案 1 :(得分:1)

您可以将GROUP BYHAVING这样使用。

<强>查询

SELECT [Dept No]
FROM departments
GROUP BY [Dept No]
HAVING SUM(CASE WHEN [Roll No] % 2 = 0 THEN 1 ELSE 0 END) > 1
AND SUM(CASE WHEN [Roll No] % 2 = 1 THEN 1 ELSE 0 END) = 0

<强>解释

如果有一个甚至使用SUM(CASE WHEN [Roll No] % 2 = 0 THEN 1 ELSE 0 END) > 1的rollno,查询将返回部门。如果有任何rollno与奇数卷no,SUM(CASE WHEN [Roll No] % 2 = 1 THEN 1 ELSE 0 END)将返回非零和,该部门将被排除。

答案 2 :(得分:0)

declare @t table (Dept int,Rno int,Student varchar(10))
insert into @t (Dept,Rno,Student)values (1,1,'lee'),(1,2,'scott'),(2,2,'scott'),(2,4,'smith'),(1,4,'smith')



SELECT Dept,Rno,Student 
FROM (SELECT ROW_NUMBER () OVER (ORDER BY Rno DESC) row_number, Dept,Rno,Student  
    FROM @t) a WHERE (row_number%2) = 0