如何从具有不同布局的两个表中选择列

时间:2014-09-12 08:54:37

标签: sql sql-server union

我有以下两个表:

一下现金出纳机

Date    PaymentId  CustId  VenId  Debit  Credit  Date
=========================================================
2/2/12  Pay_1      Cus_1                 444     3/2/2012
4/2/12  Pay_2              Ven_1  555

SalesOrder

SaleOrderId  CustId  Debit  Credit
==================================
So_1         Cus_1   666

从这两个表格中,我必须生成期刊报告,如下所示:

Date    TrId    AccountId  Debit  Credit
========================================
2/2/12  Pay_1   Cus_1             444   
3/3/12  So_1    Cus_1      666
4/2/12  Pay_2   Ven_1      555

我试过这个问题:

 SELECT *
   FROM (
        SELECT Date, PaymentId, TrId, CustId, AccountId, VenId, AccountId, Debit,
               Credit
          FROM CashRegister

         UNION

        SELECT Date, SaleOrderId, TrId, CustId, AccountId, Debit, Credit
          FROM SalesOrder
        ) t
  ORDER BY Date 

但它给出了这个错误:

  

对于目标列表,联合表达式的数量应相等。

3 个答案:

答案 0 :(得分:2)

要更正您的查询,您必须添加存根列null是通常的存根值),例如

   select * 
     from (select Date,
                  PaymentId TrId,
                  CustId AccountId,
                  VenId, 
                  Debit,
                  Credit 
             from CashRegister

            union

           select Date,
                  SaleOrderId TrId,
                  CustId AccountId,
                  null,  -- Stub: there's no verdor id
                  Debit,
                  Credit
             from SalesOrder) t 
order by Date 

然而,似乎正确的查询(返回所需的光标)是

    select Date,
           PaymentId as TrId, 
           Coalesce(CustId, VenId) as AccountId, -- if CustId is null take VenId
           Debit, 
           Credit 
      from CashRegister
 union all -- I don't think you want to remove occasional dublicates
    select Date, 
           SaleOrderId,
           CustId, 
           Debit,
           Credit
      from SalesOrder
  order by Date

答案 1 :(得分:2)

您似乎想要使用CashRegister表中的CustId或VenId,如果是这样,我认为这就是您想要的:

SELECT 
    Date, 
    PaymentId AS TrId, 
    COALESCE(CustId, VenId) AS AccountId,  -- COALESCE returns the first 
    Debit,                                 -- non null value as AccountId
    Credit     
FROM CashRegister
UNION -- use UNION ALL if you don't want to eliminate duplicate rows.
SELECT 
    Date, 
    SaleOrderId, 
    CustId, 
    Debit, 
    Credit
FROM SalesOrder
ORDER BY Date

示例SQL Fiddle

答案 2 :(得分:1)

您似乎想要使用CashRegister表中的CustId或VenId,如果是这样,我认为这就是您想要的: SELECT Date, PaymentId AS TrId, if(CustId<>'',CustId, VenId) AS AccountId, Debit, Credit
FROM CashRegister UNION SELECT Date, SaleOrderId AS TrId, CustId AS AccountId, Debit, Credit FROM SalesOrder order by Date;

编辑: 堆栈溢出格式化已剥离“&lt;&gt;”从我的代码。这将处理CustID beiang空文本,而不仅仅是CustID为NULL。