2017-03-13 5 views
0

私は、毎月のエントリを記録するSQLテーブルを持っています。毎月記録されるエントリを比較する

エントリは、.c​​svテキストファイルの内容です。

コンテンツには、主キーがName(varchar)、Description(varchar)、およびReportRan(datetime)を含む複合キーであるように繰り返す複数のフィールドがあります。私は月にしていない2月にあった行を取得する必要があり

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 

:ファイルが記録された後のような はそれが見えます。 (row3)

2月の行は1月ではありませんでした。 (row6)

月間にフィールドが変更された行。あなたが使用することができます

+0

PK =名+説明+日付? – McNets

+0

「1月にあった行と2月になかった行」と「月間にフィールドが変更された行」の違いを知るにはどうすればよいですか?値が異なる場合、主キーの定義によって行が異なります。 – bbrumm

+0

@McNetsはい主キーは複合語です。より多くのフィールドがありますが、それらは無関係で重複しています。 – toadfromgrove

答えて

1

(ROW4は)NOT EXISTS:月に= 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); 

またはON存在しない月= 2の行が存在しない月= 1の

行を月= 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

+0

2番目のクエリが終了しました。テキストファイルを調べた後、私はクエリが捕捉したものを見ますが、まだ2月のレポートには新しいエントリがありませんでした。サブクエリには、reportranに指定されたt1またはt2が必要ですか? – toadfromgrove

+0

はい、対応するエイリアスを追加することをお勧めします。 – McNets

+0

ReportRanは日付または日時フィールドですか? – McNets

関連する問題