我们可以在多列上使用NOT IN吗?

时间:2014-07-07 15:12:43

标签: sql sql-server stored-procedures where-clause

我正在创建一个涉及单个表的存储过程(带有Sql Server)。

我想将WHERE子句中的条件应用于一对列。即我想要这样的事情:

CREATE PROCEDURE afficherCreationLuns (@start DATE, @end DATE)
                    AS
                    SELECT dateMin = MIN(t1.dateCollecte), displayName, label,     date = DATEADD(day, -1, MIN(dateCollecte)), capacityInKB = MIN(capacityInKB)
                    FROM Vsp 
                    WHERE dateCollecte > @start AND dateCollecte <= @end
                                    AND (label, displayName) NOT IN (SELECT label, displayName
                                                            FROM Vsp 
                                                            WHERE dateCollecte = @start)

                    GROUP BY displayName, label

经过一些研究,我改变了代码以使用EXISTS条款,这似乎更符合我的需要。这就是我现在所拥有的:

CREATE PROCEDURE afficherCreationLuns (@start DATE, @end DATE)
                    AS
                    SELECT dateMin = MIN(t1.dateCollecte), t1.displayName, t1.label, date = DATEADD(day, -1, MIN(t1.dateCollecte)), capacityInKB = MIN(t1.capacityInKB)
                    FROM Vsp t1
                    WHERE EXISTS (SELECT t2.displayName, t2.label
                                    FROM Vsp t2
                                    WHERE t1.displayName = t2.displayName AND t1.label = t2.label AND t2.dateCollecte > @start AND t2.dateCollecte <= @end
                                    AND (t1.label NOT IN (SELECT t3.label
                                                            FROM Vsp t3
                                                            WHERE t3.dateCollecte = @start)
                                    OR t1.displayName NOT IN (SELECT t4.displayName
                                                                    FROM Vsp t4
                                                                    WHERE t4.dateCollecte = @start) ) )
                    GROUP BY t1.displayName, t1.label

但它并没有改变任何事情。

3 个答案:

答案 0 :(得分:2)

您可以将NOT IN替换为NOT EXISTS,如下所示:

SELECT
    dateMin = MIN(t1.dateCollecte)
,   t1.displayName
,   t1.label
,   date = DATEADD(day, -1, MIN(t1.dateCollecte))
,   capacityInKB = MIN(t1.capacityInKB)
FROM Vsp t1
WHERE t1.dateCollecte > @start
  AND t1.dateCollecte <= @end
  AND NOT EXISTS (
    SELECT *
    FROM Vsp t2
    WHERE t2.dateCollecte = @start
      AND t2.label=t1.label
      AND t2.displayName=t1.displayName
  )
GROUP BY t1.displayName, t1.label

我们的想法是使用匹配labeldisplayName的附加条件运行内部选择到外部选择的相应字段,并删除外部选择的记录,这样的匹配可以是找到。

答案 1 :(得分:0)

您可以将两列连接在一起吗?像这样:

SELECT *
FROM [TABLE]
WHERE COLUMN1+' '+COLUMN2
    NOT IN (
        SELECT COLUMN1+' '+COLUMN2
            FROM [OTHER-TABLE])

感谢。

答案 2 :(得分:0)

以这种方式尝试Exists子句。我不确定引用主VSP表的方法,但我认为where子句应该做你想要的。

WHERE NOT EXISTS(SELECT * FROM Vsp WHERE dateCollecte = @start AND label = Vsp.label AND displayName = Vsp.displayName)