2013-10-01 93 views
0

讓我知道如何在case語句中編寫select語句。如何在case語句中編寫select語句

select 
ROW_NUMBER() OVER(Order by vendor.VendorName) AS ID, 
PH.PurchasingHeaderID as BILLNo, 
PH.TotalPriceCompanyCurrency as Balance, 
acc.AccountName as [Account_Name] 
**Into #tempOpenVedorlist** 
from PurchasingHeader PH 
LEFT OUTER JOIN TransactionType Trans ON PH.TransactionTypeID =Trans.TransactionTypeID 
LEFT OUTER JOIN Vendor vendor on PH.VendorID=vendor.VendorID 
LEFT OUTER JOIN PaymentTerm PT on PT.PaymentTermID = vendor.PaymentTermID 
LEFT OUTER JOIN PurchasingDetail PD on PD.PurchasingHeaderID = PH.PurchasingHeaderI 
LEFT OUTER JOIN Account Acc on Acc.AccountID= PD.FinancialAccountID 
where PH.TransactionTypeID=7 
Group by vendor.VendorName, 
PH.PurchasingHeaderID,PH.TotalPriceCompanyCurrency,acc.AccountName 

我得到這個結果:

這個結果:在這裏,我沒有:VB1003兩次,但帳戶名稱是不同的。

ID  BILLNo   Account_Name   Balance 
------------------------------------------------------------- 
101  VB1000  Cash-Petty Cash   4000.00 
102  VB1001  Accounts Receivable  5000.00 
103 VB1003  Cash-PettyCash    6000.00 
104  VB1003  Cash      6000.00 
105 VB1004  UndepositedFunds   7000.00 

在這裏,我必須顯示;

我需要這樣的結果:

ID  BILLNo  Account_Name   Balance  
------------------------------------------------------ 
101  VB1000  Cash-PettyCash  4000.00 
102  VB1001  AccountsReceivable  5000.00 
103  VB1003  ---Multiple----  6000.00 
104  VB1004  UndepositedFunds  7000.00 

對於aboue結果是什麼我已經做的:我已經採取了所有的數據在臨時表。

我能夠顯示多個字符串擁有超過一個號

但不幸的是我不能夠顯示帳戶名稱爲它只有一個BILLNo。

select ROW_NUMBER() OVER(Order by BILLNo) AS ID, 
[BILLNo], 
Balance, 
CASE 
WHEN count(BILLNo)>1 THEN 'Multipul' 
WHEN count(BILLNo)<2 THEN **(Select Account_Name from #tempOpenVedorlist)** 
End As [Financial_Account] 
from #tempOpenVedorlist 
Group By BILLNo,Balance 

請讓我知道如何從臨時表中獲取與該BILLNo相關的帳戶名稱。

回答

2

GROUP BY中刪除AccountName並在其上放置一個聚合。

SELECT ROW_NUMBER() OVER(Order by vendor.VendorName) AS ID, 
     PH.PurchasingHeaderID as BILLNo, 
     PH.TotalPriceCompanyCurrency as Balance, 
     CASE WHEN MIN(acc.AccountName) IS NULL 
      THEN '----' 
      WHEN MIN(acc.AccountName) = MAX(acc.AccountName) 
      THEN MIN(acc.AccountName) 
      ELSE '--MULTIPLE--' 
     END as [Account_Name] 
INTO #tempOpenVedorlist 
FROM PurchasingHeader PH 
     LEFT OUTER JOIN TransactionType Trans 
      ON PH.TransactionTypeID =Trans.TransactionTypeID 
     LEFT OUTER JOIN Vendor vendor 
      ON PH.VendorID=vendor.VendorID 
     LEFT OUTER JOIN PaymentTerm PT 
      ON PT.PaymentTermID = vendor.PaymentTermID 
     LEFT OUTER JOIN PurchasingDetail PD 
      ON PD.PurchasingHeaderID = PH.PurchasingHeaderI 
     LEFT OUTER JOIN Account Acc 
      ON Acc.AccountID= PD.FinancialAccountID 
WHERE PH.TransactionTypeID=7 
GROUP BY vendor.VendorName, 
     PH.PurchasingHeaderID, 
     PH.TotalPriceCompanyCurrency 
+0

如果我從集團的,我得到錯誤,如刪除的帳戶名稱:列「Account.AccountName」,因爲它不是在聚合函數或GROUP BY子句包含在選擇列表中無效。 – Kavitha

+1

我想你會在THEN中需要一個'MIN()',因爲那時候仍然有多行可能。 –

+0

請現在檢查。我全部包含在MAX中,所以它應該可以工作。 –