查询错误并将结果查询加载到新表

时间:2017-05-25 13:46:08

标签: sql sql-server

任何人都可以通过以下查询纠正我的查询出错的地方吗? 对于下面的Query,我需要添加where子句并根据客户端名称获取。当我执行查询时,我只能查看第一个客户端数据。而且我希望结果存储在单独的数据库中。

select  amount,[Account #]as cdn#,[CC ACCT]as CC#,[CardType] as CCType 
  from [PayPal_staging].[dbo].[VendorFiles] as a
  inner join [CUBS].[dbo].[Client] as d
  on d.PK_Client=CONVERT(varchar(250),a.client)
Union all
  Select [Amount],[CDN #] as cdn#,[Card_No] as CC#,[Card_Type] as CCType 
  from [PayPal_staging].[dbo].[VirtualFiles] as b
  left join [CUBS].[dbo].[Client] as d
  on d.PK_Client=CONVERT(varchar(250),b.[Client_Id])
  union all
  select [SV10_Amt] as Amount,[Cdr_Id] as cdn#,[SV07_Last4] as CC#,[CardType] as CCType
  from [PayPal_staging].[dbo].[IVRFiles] as c
  left join [CUBS].[dbo].[Client] as d
  on d.PK_Client=CONVERT(varchar(250),c.[SV03_Clientnbr])
  where PK_Client in ('SWMC600',' SQMC203',' SQMC600',' SBMC203',' SBMC600',
' PROV203',' PROV600',' SWRC203',' SWRC600',' SMCC203',' SMCC600',' SWIS203',' SWIS600')

任何人都可以帮我查询出错的上述查询以及如何在Where子句中获取所有客户端的结果以及如何将结果存储在单独的数据库中? 请写一个完整的上述任务查询......

2 个答案:

答案 0 :(得分:1)

很难确定,但除了第一个客户ID之外,每个客户ID都有一个空格:

where PK_Client in ('SWMC600',' SQMC203',' SQMC600',' SBMC203',' SBMC600',
    ' PROV203',' PROV600',' SWRC203',' SWRC600',' SMCC203',' SMCC600',
    ' SWIS203',' SWIS600')

只需删除空格:

where PK_Client in ('SWMC600','SQMC203','SQMC600','SBMC203','SBMC600',
    'PROV203','PROV600','SWRC203','SWRC600','SMCC203','SMCC600',
    'SWIS203','SWIS600')

答案 1 :(得分:0)

where子句仅适用于最后一个选择。也许你想要这样。

SELECT *
FROM (SELECT  [Amount]
        , [Account #]as cdn#
        , [CC ACCT]as CC#
        , [CardType] as CCType 
        , PK_Client
    FROM [PayPal_staging].[dbo].[VendorFiles] AS a
    INNER JOIN [CUBS].[dbo].[Client] AS d
      ON d.PK_Client=CONVERT(varchar(250),a.client)
    UNION ALL
    SELECT [Amount]
        , [CDN #] AS cdn#
        , [Card_No] AS CC#
        , [Card_Type] AS CCType 
        , PK_Client
    FROM [PayPal_staging].[dbo].[VirtualFiles] AS b
    LEFT JOIN [CUBS].[dbo].[Client] as d
        ON d.PK_Client=CONVERT(varchar(250),b.[Client_Id])
    UNION ALL
    SELECT [SV10_Amt] AS Amount
        , [Cdr_Id] AS cdn#
        , [SV07_Last4] AS CC#
        , [CardType] AS CCType
        , PK_Client
    FROM [PayPal_staging].[dbo].[IVRFiles] AS c
    LEFT JOIN [CUBS].[dbo].[Client] AS d
        ON d.PK_Client=CONVERT(varchar(250),c.[SV03_Clientnbr])
) t
WHERE t.PK_Client IN ('SWMC600','SQMC203','SQMC600','SBMC203','SBMC600'
,'PROV203','PROV600','SWRC203','SWRC600','SMCC203','SMCC600'
,'SWIS203','SWIS600');