SQL Union不显示所有结果

时间:2017-10-24 10:52:08

标签: sql sql-server tsql union

我正在尝试显示信用列和借记列,但它将两个金额都放在一列中,并且只显示信用标题。

对于每个陈述说明,都有信用卡和借记金额。 我需要它填充,以便我可以看到Statement_description = credit 以及statement_description debit

`SELECT PR.[Statement_Description]
      --,PR.[Debit_Acc_Num]
      ,PR.[Credit_Acc_Num]
      ,PR.Actual_Txn_Amount as Credit_Amount
      ,Actual_Txn_Date
      ,PBY = '949'
      ,VatCode = 'E'

         FROM [Financial].[dbo].[Payment_Request] PR
             inner join SharedData.dbo.StaffData SD
                on PR.Prepared_By = SD.StaffNo 
  where  
   ID_Payment_Status = '1'
  --and Prepared_By_Date = (SELECT CONVERT(DATETIME, CONVERT(DATE, CURRENT_TIMESTAMP)) + '14:00' as date )
  and (Debit_Acc_Num  like '1%' or Debit_Acc_Num like'2%') 
  and (Credit_Acc_Num like '1%' or Credit_Acc_Num like'2%') 
  and Debit_Acc_Num <> 0
  --and Credit_Acc_Num <> 0

union  

  SELECT PR.[Statement_Description]
      ,PR.[Debit_Acc_Num]
      --,PR.[Credit_Acc_Num]
      ,PR.Actual_Txn_Amount as Debit_Amount 
      ,Actual_Txn_Date
      ,PBY = '949'
      ,VatCode = 'E'

     FROM [Financial].[dbo].[Payment_Request] PR
             inner join SharedData.dbo.StaffData SD
                on PR.Prepared_By = SD.StaffNo 
  where  
   ID_Payment_Status = '1'
  and (Debit_Acc_Num like '1%' or Debit_Acc_Num like'2%') 
  and (Credit_Acc_Num like '1%' or Credit_Acc_Num like'2%') 
  --and Debit_Acc_Num <> 0
  and Credit_Acc_Num <> 0
    order by Statement_Description
`

1 个答案:

答案 0 :(得分:1)

你可以这样做,采取&#39; 0&#39;作为第一个联合中的DebitAmount和作为originalAmount的Credit,然后在下一个联合中为Credit执行相同的操作。

  SELECT PR.[Statement_Description]
  --,PR.[Debit_Acc_Num]
  ,PR.[Credit_Acc_Num]
  ,0 as DebitAmount
  ,PR.Actual_Txn_Amount as Credit_Amount
  ,Actual_Txn_Date
  ,PBY = '949'
  ,VatCode = 'E'

     FROM [Financial].[dbo].[Payment_Request] PR
         inner join SharedData.dbo.StaffData SD
            on PR.Prepared_By = SD.StaffNo 
where  
ID_Payment_Status = '1'
--and Prepared_By_Date = (SELECT CONVERT(DATETIME, CONVERT(DATE, 
CURRENT_TIMESTAMP)) + '14:00' as date )
and (Debit_Acc_Num  like '1%' or Debit_Acc_Num like'2%') 
and (Credit_Acc_Num like '1%' or Credit_Acc_Num like'2%') 
and Debit_Acc_Num <> 0
--and Credit_Acc_Num <> 0

union  

SELECT PR.[Statement_Description]
  ,PR.[Debit_Acc_Num]
  --,PR.[Credit_Acc_Num]
  ,PR.Actual_Txn_Amount as Debit_Amount 
  ,0 as CreditAmount
  ,Actual_Txn_Date
  ,PBY = '949'
  ,VatCode = 'E'

 FROM [Financial].[dbo].[Payment_Request] PR
         inner join SharedData.dbo.StaffData SD
            on PR.Prepared_By = SD.StaffNo 
 where  
 ID_Payment_Status = '1'
and (Debit_Acc_Num like '1%' or Debit_Acc_Num like'2%') 
  and (Credit_Acc_Num like '1%' or Credit_Acc_Num like'2%') 
--and Debit_Acc_Num <> 0
and Credit_Acc_Num <> 0
order by Statement_Description