比较每月记录的条目

时间:2017-03-13 18:36:06

标签: sql compare sql-server-2014

我有一个记录月度条目的SQL表。

条目是.csv文本文件的内容。

内容有多个重复的字段,因此主键是包含Name(varchar),Description(varchar)和ReportRan(datetime)的复合键。 记录文件后,它看起来像:

 Name | Description | ReportRan
comp1 | some data   | 2017-01-01
comp1 | more data   | 2017-01-01
comp1 | even more   | 2017-01-01
comp1 | s0me data   | 2017-02-01
comp1 | more data   | 2017-02-01
comp1 | new data    | 2017-02-01

我需要获得1月份而不是2月份的行。 (ROW3)

二月的行不是一月份。 (ROW6)

在几个月之间有字段变化的行。 (ROW4)

1 个答案:

答案 0 :(得分:1)

您可以使用NOT EXISTS:

月份= 1但在月份= 2

上不存在
select t1.Name, t1.Description, t1.ReportRan
from   your_table t1
where  month(t1.ReportRan) = 1
and    not exists (select 1
                  from your_table t2
                  where t1.Name = t2.Name
                  and   t1.Description = t2.Description
                  and   month(t2.ReportRan) = 2);

月份= 1的行= 2在月份= 1

上不存在
select t1.Name, t1.Description, t1.ReportRan
from   your_table t1
where  month(t1.ReportRan) = 2
and    not exists (select 1
                  from your_table t2
                  where t1.Name = t2.Name
                  and   t1.Description = t2.Description
                  and   month(t2.ReportRan) = 1);

到目前为止,为了获得所有行,我已经使用了先前查询的UNION。

select t1.Name, t1.Description, t1.ReportRan
from   @tbl t1
where  month(t1.ReportRan) = 1
and    not exists (select 1
                  from @tbl t2
                  where t1.Name = t2.Name
                  and   t1.Description = t2.Description
                  and   month(t2.ReportRan) = 2)
UNION
select t1.Name, t1.Description, t1.ReportRan
from   @tbl t1
where  month(t1.ReportRan) = 2
and    not exists (select 1
                  from @tbl t2
                  where t1.Name = t2.Name
                  and   t1.Description = t2.Description
                  and   month(t2.ReportRan) = 1);


|Name |Description|ReportRan          |
|:----|:----------|:------------------|
|comp1|some data  |01/01/2017 00:00:00|
|comp1|even more  |01/01/2017 00:00:00|

|Name |Description|ReportRan          |
|:----|:----------|:------------------|
|comp1|s0me data  |01/02/2017 00:00:00|
|comp1|new data   |01/02/2017 00:00:00|

|Name |Description|ReportRan          |
|:----|:----------|:------------------|
|comp1|even more  |01/01/2017 00:00:00|
|comp1|new data   |01/02/2017 00:00:00|
|comp1|s0me data  |01/02/2017 00:00:00|
|comp1|some data  |01/01/2017 00:00:00|

dbfiddle here