从内部查询返回多列以解决错误时如何修改查询

时间:2019-04-09 18:56:27

标签: sql-server

我有一个复杂的查询,其中我的内部查询产生正确的结果。但是由于我的子查询返回的值比列上的要多,所以我收到错误“ Only one expression can be specified in the select list when the sub query is not introduced with EXISTS

我应该如何修改查询以解决错误,但我需要相同数量的内部查询列。

SQL Server 2012查询

select Distinct 
   s.SalesInvoiceID,
   cust.CustomerID,
   cust.Name,
   cust.FName,
   cust.CustomerCNIC,   

   CASE WHEN s.SpecialInsttPlan = 'No' 

   THEN 
        (s.TotalBill - s.Advance) / s.Installments
   ELSE
   (
        select Distinct Top 1 sip.Amount,iph.InsttNo
        from
        SpecialInsttPlan sip 
        join InstallmentPaymentHistory iph
        on iph.InsttNo=sip.InsttNo
        where
        sip.SalesInvoiceID=45 and iph.SalesInvoiceID=45 and 
        (iph.Status ='Pending' or iph.Status ='Up Coming') order by iph.InsttNo
    )

   END as Installment,
   s.TotalBill - s.Advance - sum(iph.Amount)   as BalanceAmount

from
   SalesInvoice s 
   inner join
      InstallmentPaymentHistory iph 
      on iph.SalesInvoiceID = s.SalesInvoiceID 
   inner join
      Customer cust 
      on s.CustomerID = cust.CustomerID 
where
   iph.SalesInvoiceID = 45
group by
   s.SalesInvoiceID,
   s.TotalBill,
   s.Installments,
   s.Discount,
   s.Advance,
   cust.Name,
   cust.FName,
   cust.CustomerID,
   cust.CustomerCNIC,
   s.SpecialInsttPlan,
   iph.InsttNo

1 个答案:

答案 0 :(得分:0)

select a.SalesInvoiceID,a.CustomerID,a.Name,a.FName,a.CustomerCNIC,

    CASE WHEN a.SpecialInsttPlan = 'No' 

    then 
        a.Installment
    else ( select sip.Amount from SpecialInsttPlan sip 
            where  a.Installment=sip.InsttNo and sip.SalesInvoiceID=44
          ) 
            end as Installment,a.BalanceAmount
from 

(
select Distinct
   s.SalesInvoiceID,
   cust.CustomerID,
   cust.Name,
   cust.FName,
   cust.CustomerCNIC,
   s.SpecialInsttPlan,

   CASE WHEN s.SpecialInsttPlan = 'No' 

   THEN 
        (s.TotalBill - s.Advance) / s.Installments 
   ELSE
   (
         select Distinct Top 1 iph.InsttNo
         from
            SpecialInsttPlan sip 
            join InstallmentPaymentHistory iph
            on iph.InsttNo=sip.InsttNo
         where
        sip.SalesInvoiceID=44 and iph.SalesInvoiceID=44 and 
        (iph.Status ='Pending' or iph.Status ='Up Coming')   order by iph.InsttNo


    )
   END as Installment, 
   s.TotalBill - s.Advance - sum(iph.Amount)   as BalanceAmount

from
   SalesInvoice s 
   inner join
      InstallmentPaymentHistory iph 
      on iph.SalesInvoiceID = s.SalesInvoiceID 
   inner join
      Customer cust 
      on s.CustomerID = cust.CustomerID 
where
   iph.SalesInvoiceID = 44
group by
   s.SalesInvoiceID,
   s.TotalBill,
   s.Installments,
   s.Discount,
   s.Advance,
   cust.Name,
   cust.FName,
   cust.CustomerID,
   cust.CustomerCNIC,
   s.SpecialInsttPlan) as a

由于内部只能返回一列,因此我使用了另一个外部查询,并且在内部查询中仅使用了一列