3

您好,非常感谢您抽出宝贵时间。我正在使用 SQL Server 2008。我的挑战如下:

我有 3 个数据库Q_DB, CAN_DB, USA_DB. CAN_DB并且USA_DB有相同的表格,但代表两个不同的国家

Q_DB队列表。一个表被调用ACCOUNTS,感兴趣的列是ACCOUNTIDSERVER

我想从.的字段中查询其他两个数据库的信息ACCOUNTS。一个例子是:

Q_DB.dbo.ACCOUNTS

  • ID123 CAN_DB
  • ID456 USA_DB
  • ID789 CAN_DB

我知道我可以这样做,但我想知道是否有其他方法可以获得结果。

SELECT ACTNAME, AMTDUE, SHIPCOUNTY  
FROM CAN_DB.dbo.Accts 
WHERE ACCTID IN(SELECT ACCOUNTID FROM Q_DB.dbo.ACCOUNTS WHERE SERVER IN('CAN_DB')
UNION ALL
SELECT ACTNAME, AMTDUE, SHIPCOUNTRY 
FROM USA_DB.dbo.Accts
WHERE ACCTID IN(SELECT ACCOUNTID FROM Q_DB.dbo.ACCOUNTS WHERE SERVER IN('USA_DB')

任何帮助或意见或建议将不胜感激。谢谢

4

1 回答 1

3

我不明白您为什么使用IN单个值(CAN_DB)。

此外,您应该预先识别EXISTS而不是IN.

SELECT ACTNAME, AMTDUE, SHIPCOUNTRY  
FROM CAN_DB.dbo.Accts a1
WHERE EXISTS (SELECT * FROM Q_DB.dbo.ACCOUNTS WHERE ACCTID = a1.ACCTID AND SERVER = 'CAN_DB')
UNION ALL
SELECT ACTNAME, AMTDUE, SHIPCOUNTRY 
FROM USA_DB.dbo.Accts a2
WHERE EXISTS (SELECT * FROM Q_DB.dbo.ACCOUNTS WHERE ACCTID = a2.ACCTID AND SERVER = 'USA_DB')

注意:使用UNION ALL将返回重复项(如果有的话)。要让查询选择唯一行,请改用关键字UNION

编辑:如果你想AMTDUE根据相同的ACTNAME和从两台服务器求和SHIPCOUNTRY

SELECT  COALESCE(can.ACTNAME,usa.ACTNAME) as ACTNAME,
        COALESCE(can.AMTDUE,0)+COALESCE(usa.AMTDUE,0) as AMTDUE,
        COALESCE(can.SHIPCOUNTRY,usa.SHIPCOUNTRY) as SHIPCOUNTRY  
FROM    CAN_DB.dbo.Accts can
FULL OUTER JOIN USA_DB.dbo.Accts usa
ON      can.ACTNAME = usa.ACTNAME AND 
        can.SHIPCOUNTRY = usa.SHIPCOUNTRY
于 2012-10-22T18:03:48.697 回答