如何检查列表是否具有任何不同的值

时间:2010-08-12 18:13:16

标签: sql sql-server tsql operators logic

我有一张如下表格:

(date1, date2, date3, date4, date5)

我想检查这些日期中的任何一个是否与其他日期不同。 简单的解决方案是:

WHERE date1 <> date2
   OR date1 <> date3
   OR date1 <> date4
   OR date1 <> date5
   OR date2 <> date3
   OR date2 <> date4
   OR date2 <> date5
   OR date3 <> date4
   OR date3 <> date5
   OR date4 <> date5

任何重要的解决方案?

5 个答案:

答案 0 :(得分:5)

除此之外,你的琐碎案例可以简化为

WHERE date1 <> date2
   OR date1 <> date3
   OR date1 <> date4
   OR date1 <> date5

使用DeMorgan's Law,这与

相同
WHERE NOT(date1 = date2
      AND date1 = date3
      AND date1 = date4
      AND date1 = date5)

然后通过transitive propertyequality relation,我们知道如果date1等于其他4个值,那么所有5个值都相等。

答案 1 :(得分:2)

如果表有主键,我想这不是一件容易的事。

select key, "There are duplicates"
from
(
    select key,date1 from table
    union all
    select key,date2 from table
    union all
    select key,date3 from table
    union all
    select key,date4 from table
    union all
    select key,date5 from table
) as aa
group by
  key, date1
having 
  count(*) > 1

答案 2 :(得分:0)

按每个值分组,将按组计数与原始计数进行比较

答案 3 :(得分:0)

如果您使用的是SQL Server 2005+,则可以执行以下操作:

With Dates As
    (
    Select PK, 'Date1' As DateType, Date1 As [Date] From Table
    Union All Select PK, 'Date2', Date2 From Table
    Union All Select PK, 'Date3', Date3 From Table
    Union All Select PK, 'Date4', Date4 From Table
    Union All Select PK, 'Date5', Date5 From Table
    )
Select D.PK, D.DateType, D.[Date]
From Dates As D
Where Exists    (
                Select 1
                From Dates As D1
                Where D1.PK = D.PK
                    And D1.[Date] <> D.[Date]
                )

答案 4 :(得分:0)

这对我来说更容易用一个例子来描绘。这有效,但我不确定我是否过于复杂。

CREATE TABLE #Dates( ID int, date1 datetime, date2 datetime, date3 datetime, date4 datetime )
INSERT INTO #Dates VALUES( 1, '1 Jan 2008', '2 Feb 2979', '8 Nov 1967', '31 Dec 2001' ) 
INSERT INTO #Dates VALUES( 2, '1 Jan 2008', '1 Jan 2008', '1 Jan 2008', '1 Jan 2008' ) 
INSERT INTO #Dates VALUES( 3, '1 Jan 2008', '1 Jan 2008', '1 Jan 2008', '31 Jan 2008' ) 
INSERT INTO #Dates VALUES( 4, '1 Jan 2008', '1 Jan 2008', '31 Jan 2008', '1 Jan 2008' ) 

-- look at example data - note only row 2 has all 4 dates the same
SELECT * FROM #Dates

-- return rows where the dates are not all the same 
SELECT ID as RowsWithDatesNotAllTheSame
FROM 
    (
    SELECT ID, Date
    FROM 
        (
        SELECT ID, DateCol, Date
        FROM 
            (SELECT ID, date1, date2, date3, date4 
            FROM #Dates) p 

        UNPIVOT
            ( Date FOR DateCol IN
                (date1, date2, date3, date4)
        ) AS unpvt
        ) x
    GROUP BY ID, Date
    ) y 
GROUP BY ID
HAVING count(*) > 1