【问题标题】:Two query in single result table?单个结果表中的两个查询?
【发布时间】:2011-09-13 13:40:42
【问题描述】:

我是 SQL Server 2008 的新手。有一个 Proc。在这个 Proc 中,我有两个 select 语句。当我执行我的 Proc 时,我会在我接受的两个表中得到结果。但我想在单个表中返回。

我的进程 -

 ALTER PROC [GetPaymentGateway]  
 @CompanyID VARCHAR(3),  
 @ChannelType varchar(15)=null
AS  

IF @ChannelType='BODC' OR @ChannelType='BO-DC'  
BEGIN
    SELECT [card_name], [card_type], [BODC_Amount], [BODC_Amount_Type], PGM.PG_Type FROM credit_card_master CCM
    INNER JOIN PaymentGateway_master PGM
    ON PGM.payment_gateway_code = CCM.payment_gateway_code  
    WHERE CCM.company_id = @CompanyID and CCM.disabled = '1'

    SELECT PGM.Payment_Gateway_Name, PGNBC.BODC_Charge_Amt, PGNBC.BODC_Charge_type, PGM.PG_Type 
    FROM PG_NetBanking_Charges PGNBC
    INNER JOIN PaymentGateway_master PGM
    ON PGM.payment_gateway_code = PGNBC.payment_gateway_code
    WHERE PGNBC.company_id = @CompanyID
END

IF @ChannelType='B2C' OR @ChannelType='ONLINE-DC'  
BEGIN
    SELECT [card_name], [card_type], [charge_amount], [B2C_Amount_type], PGM.PG_Type FROM credit_card_master CCM
    INNER JOIN PaymentGateway_master PGM
    ON PGM.payment_gateway_code = CCM.payment_gateway_code 
    WHERE CCM.company_id = @CompanyID and CCM.disabled = '1' 

    SELECT PGM.Payment_Gateway_Name, PGNBC.Online_DC_Charge_Amt, PGNBC.Online_DC_Charge_type, PGM.PG_Type 
    FROM PG_NetBanking_Charges PGNBC
    INNER JOIN PaymentGateway_master PGM
    ON PGM.payment_gateway_code = PGNBC.payment_gateway_code
    WHERE PGNBC.company_id = @CompanyID
END 

请建议我怎么可能??

提前致谢。

【问题讨论】:

    标签: sql-server-2005 stored-procedures


    【解决方案1】:

    要将两个查询合并到一张表中,您需要UNION 操作。这需要两个结果集,并且基本上将它们粘合在一起。
    Union 的限制很少,最重要的是查询必须具有相同的列数。

    在您的查询中,您选择了不同数量的列,credit_card_master 查询各有 5 列,PG_NetBanking_Charges 查询各有 4 列。

    据我所知,我猜第一个查询中的 card_type 列在第二个查询中没有等效项,因此您可以将第二个查询重写为:

    SELECT card_name, card_type, charge_amount, B2C_Amount_type, PGM.PG_Type 
      FROM ...
      WHERE ...
    UNION
    SELECT PGM.Payment_Gateway_Name, null, PGNBC.Online_DC_Charge_Amt,
           PGNBC.Online_DC_Charge_type, PGM.PG_Type
      FROM ...
      WHERE ...
    

    另请注意,结果集中的列将采用第一个查询中列的名称,因此您可能需要添加列别名以获得更有意义/通用的列名称。此外,我通常添加一个“源”列,使我能够跟踪联合中行的来源,因此我的最终查询如下所示:

    SELECT 1 as Source, card_name as Name, card_type as Type, 
           charge_amount as Ammount, B2C_Amount_type as AmmountType,
           PGM.PG_Type as PG_Type
      FROM ...
      WHERE ...
    UNION
    SELECT 2, PGM.Payment_Gateway_Name, null, PGNBC.Online_DC_Charge_Amt,
           PGNBC.Online_DC_Charge_type, PGM.PG_Type
      FROM ...
      WHERE ...
    

    结果将包含 SourceNameTypeAmmountAmmountTypePG_Type 列,其中 Source 将是 1 表示第一行,而 2 表示来自第二个查询的行。

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多