如何使用case语句比较psql中的两个表

时间:2016-04-19 12:14:22

标签: psql

我有两个表的定义相同但记录不同 一张桌子有今天的日期,另一张桌子有昨天的数据: -

表A--今天的数据

name,name_code,start_dt,  subname,subname_code,subname_st_date
abc   Active   12-04-1026 abc1    Active       13-042016
def   Active   23-03-2016  def987 Active       23-01-2016

表B - 昨天的数据

name,name_code,start_dt,  subname,subname_code,subname_st_date
abc   Inactive 12-04-1026 abc1    Active       13-042016
def   Active   24-03-2016  def987 Inactive       23-01-2016
def   Active   24-02-2016  def876 Inactive       23-01-12016

我的要求是比较表和输出应该是下面记录的差异

例如:---

Subname were Cancelled : def987
New subname added :     def876

请帮助。

1 个答案:

答案 0 :(得分:0)

select coalesce(
  case 
    when b.subname_code = 'Inactive' 
    then 'Subname were Cancelled :'
    else 'New subname added      :'
  end
  , b.subname) 
from tableb b
left outer join tablea a on a.subname = b.subname
where a.subname_code <> b.subname_code or a.subname_code is null;