不同条件(类似于IF)+唯一值

时间:2019-07-09 16:33:43

标签: sql sql-server tsql

我需要使用不同的条件过滤数据。一个是如果一个列(d列)中的值是唯一的,如果另一列(c)中的值大于1,则我需要质疑。

让我们假设: 栏a,b,c,d

因此,我不希望任何条目,其中c大于1而d具有非唯一值。

Select TOP 100 * From table
Where (a = 'Max' AND b = '2019') -- just an additional filter, which always applies
    AND (c = 1 -- if c is one, that is fine
            OR (c > 1 AND -- here I want to check if c is bigger than 1 AND if d is unique; but thats the part I need help with
        );

非常感谢您!

1 个答案:

答案 0 :(得分:0)

创建一个CTE,您可以在其中计算列d的不同值,并在WHERE子句中使用它:

with cte as (
  select count(distinct d) counter from tablename
)
...........................................
Where ....(c > 1 AND (select counter from cte) = 1)