ようこそ ゲスト さん、新規登録(無料)して気になる疑問を解決しませんか?

質問

QNo.3501968 diffに相当するSQL文
質問者:bsml SQLを書けなく困っています。お願いします。

「社員住所2007年」と「社員住所2006年」まったく同じ項目のテーブルがあるとします。社員数は多少増減します。

二つのテーブルを比較し、2007年の変わったレコードの変わった項目だけを取り出したいんです。

お願いいたします。
困り度:
  • すぐに回答を!
質問投稿日時:
07/11/09 01:20
この質問に対する回答は締め切られました。

回答良回答20pt

ANo.1 RDBMSは、このカテゴリ通りSQL Serverですか?
2000ですか?2005ですか?

こういった操作では「FULL JOIN」をすぐに思いつくのですが、「FULL JOINを未実装のRDBMS」や「実装していてもバージョンが新しくないとだめ」といったケースがあります。もし、「FULL JOIN」が未実装の場合は、「LEFT JOIN」+「RIGHT JOIN」+「UNION」で実現することが可能です。

>二つのテーブルを比較

比較するには、行を一意に識別できるキーが必要です。社員Noをキーにするということでいいですか?

>変わったレコードの変わった項目だけを取り出したい

項目数を可変にすることは、SQLだけでは困難です。
変更内容を知るには、変更前と変更後の情報がないと困るでしょ?

SQL例を提示します。
「丸投げ」的な質問の仕方をしているのですから、何をやっているかくらいは自分なりに調べたり試行錯誤してみましょう!

select
coalesce(x.EmpNo,y.EmpNo) as EmpNo,
case when x.EmpName is null and y.EmpName is null then null
when x.EmpName is null and y.EmpName is not null then 'null=>('+y.EmpName+')'
when x.EmpName is not null and y.EmpName is null then '('+x.EmpName+')=>null'
when x.EmpName=y.EmpName then '='+'('+x.EmpName+')'
else '('+x.EmpName+')<=>('+y.EmpName+')'
end as EmpName,
case when x.EmpSection is null and y.EmpSection is null then null
when x.EmpSection is null and y.EmpSection is not null then 'null=>('+y.EmpSection+')'
when x.EmpSection is not null and y.EmpSection is null then '('+x.EmpSection+')=>null'
when x.EmpSection=y.EmpSection then '='+'('+x.EmpSection+')'
else '('+x.EmpSection+')<=>('+y.EmpSection+')'
end as EmpSection,
case when x.EmpAddr is null and y.EmpAddr is null then null
when x.EmpAddr is null and y.EmpAddr is not null then 'null=>('+y.EmpAddr+')'
when x.EmpAddr is not null and y.EmpAddr is null then '('+x.EmpAddr+')=>null'
when x.EmpAddr=y.EmpAddr then '='+'('+x.EmpAddr+')'
else '('+x.EmpAddr+')<=>('+y.EmpAddr+')'
end as EmpAddr
from Emp2006 as x
full join Emp2007 as y
on x.EmpNo=y.EmpNo
order by EmpNo
回答者:chukenkenkou
種類:アドバイス
どんな人:専門家
自信:参考意見
回答日時:
07/11/09 06:09
この回答へのお礼ご回答たいへんありがとうございます。
載せていただいた例文で、大変参考になり、さまざまの場面に応用させていただいております。これほど役にたった回答は今までなかったくらいです。
まことにありがとうございました。