Sql server 如何在MSSQL中查找两个表之间的差异

Sql server 如何在MSSQL中查找两个表之间的差异,sql-server,Sql Server,我有两张“顾客”桌 第一个: ID | UserID | Date 1. | 1 | 2018-05-01 2. | 1 | 2018-05-02 第二条: ID | UserID | Date 1. | 1 | 2018-05-01 2. | 1 | 2018-05-02 3. | 1 | 2018-05-03 因此,正如您在第二个表中看到的,还有一行。 到目前为止,我已经编写了以下代码: ;with cte_table1 as ( s

我有两张“顾客”桌

第一个:

ID | UserID | Date 
1. |   1    | 2018-05-01
2. |   1    | 2018-05-02
第二条:

ID | UserID | Date 
1. |   1    | 2018-05-01
2. |   1    | 2018-05-02
3. |   1    | 2018-05-03
因此,正如您在第二个表中看到的,还有一行。 到目前为止,我已经编写了以下代码:

;with cte_table1 as (
select UserID, count(id) cnt from db1.Customer group by UserID
),
cte_table2 as (
select UserID, count(id) cnt from db2.Customer group by UserID
)
select * from cte_table1 t1
join cte_table2 t2 on t2.UserID = t1.UserID
where t1.cnt <> t2.cnt
到目前为止,一切都很好。问题是,这两个表有很多行,我希望得到带有日期的结果,其中cnt不匹配

换句话说,我想要这样的东西:

    UserID | cnt |     Date    | UserID | cnt |    Date
       1   |  2  | 2018-05-01  |  1     |  3  | 2018-05-01
       1   |  2  | 2018-05-02  |  1     |  3  | 2018-05-01
       1   |  2  |    NULL     |  1     |  3  | 2018-05-03
最好的解决方案是将两个cte连接在一起的结果集:

    UserID | cnt |     Date    | UserID | cnt |    Date
       1   |  2  | 2018-05-01  |  1     |  3  | 2018-05-01
       1   |  2  | 2018-05-02  |  1     |  3  | 2018-05-01
       1   |  2  |    NULL     |  1     |  3  | 2018-05-03
       1   |  2  | 2018-05-30  |  1     |  3  | NULL
您应该执行如下的查询

Select 
  C1.UserID,
  C1.cnt,
  C1.Date,
  C2.UserID,
  C2.cnt,
  C2.Date
from
db1.Customer C1
FULL OUTER JOIN
db2.Customer C2
on C1.UserId=C2.UserId and C1.date=C2.Date

我想您正在寻找
除了
也许您想要的是
完全外部连接
?也许吧,但是如何在结果中添加日期呢?我卡住了,不知道该怎么走。这不管用,不过还是谢谢你。我自己做的。
Select 
  C1.UserID,
  C1.cnt,
  C1.Date,
  C2.UserID,
  C2.cnt,
  C2.Date
from
db1.Customer C1
FULL OUTER JOIN
db2.Customer C2
on C1.UserId=C2.UserId and C1.date=C2.Date