SQL Server:返回一列不同的记录

时间:2013-10-04 19:12:50

标签: sql-server

我试图从一张桌子上找到。一列不匹配的所有记录。我还需要基于无与伦比的条目来遵循某些情况的日期。

实施例

record     COL1|COL2|COL3|  COL4  |  COL 5
1)          A    B    X    1/20/13   1/20/13
2)          A    B    Y    1/15/13   1/16/13
3)          B    D    X    2/14/13   2/16/13
4)          B    D    Y    2/15/13   4/09/13

我需要的是(以记录1和2为例):

  • COL1 = COL1 AND COL2 = COL2

  • COL3<> COL3(在COL3中仅存在条目X或Y。

  • 记录2上的COL4在记录1上是> = COL5

换句话说;我需要COL1和COL2重复的所有记录,但COL3是唯一的;此外,Y的记录必须具有COL4> =记录X COL5 -7days

1 个答案:

答案 0 :(得分:0)

SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE Table1
    ([record] int, [COL1] varchar(1), [COL2] varchar(1), [COL3] varchar(1), [COL4] date, [COL5] date)
;

INSERT INTO Table1
    ([record], [COL1], [COL2], [COL3], [COL4], [COL5])
VALUES
    (1, 'A', 'B', 'X', '2013-01-20', '2013-01-20'),
    (2, 'A', 'B', 'Y', '2013-01-15', '2013-01-16'),
    (3, 'B', 'D', 'X', '2013-02-14', '2013-02-16'),
    (4, 'B', 'D', 'Y', '2013-02-15', '2013-04-09'),
    (5, 'C', 'E', 'X', '2013-02-14', '2013-02-16'),
    (6, 'C', 'E', 'Y', '2013-01-15', '2013-02-09')
;

查询1

SELECT t1.*
FROM Table1 t1
INNER JOIN Table1 t2 ON t1.col1 = t2.col1 AND
                        t1.col2 = t2.col2 AND  
                        t1.col3 <> t2.col3 AND
                        t2.col4 >= dateadd(dd,-7,t1.col5)
WHERE t1.col3 = 'X'
UNION
SELECT t2.*
FROM Table1 t1
INNER JOIN Table1 t2 ON t1.col1 = t2.col1 AND
                        t1.col2 = t2.col2 AND  
                        t1.col3 <> t2.col3 AND
                        t2.col4 >= dateadd(dd,-7,t1.col5)
WHERE t1.col3 = 'X'

<强> Results

| RECORD | COL1 | COL2 | COL3 |       COL4 |       COL5 |
|--------|------|------|------|------------|------------|
|      1 |    A |    B |    X | 2013-01-20 | 2013-01-20 |
|      2 |    A |    B |    Y | 2013-01-15 | 2013-01-16 |
|      3 |    B |    D |    X | 2013-02-14 | 2013-02-16 |
|      4 |    B |    D |    Y | 2013-02-15 | 2013-04-09 |