2012-06-05 49 views
0

我只是浪費這個Sql Transact後面的兩到三個Hourse,並且混淆了空值Skip。Sql空值在一列分區

我有兩個表如下圖所示:

Table 1: AccountMast 
companyID accname   category 
102  PURCHASE ACCOUNT Purchase Account 
102  SALES ACCOUNT  Sales Account 

Table2: Legder 

companyID name    
102  PURCHASE ACCOUNT   
102  SALES ACCOUNT  

我有如下加入吧:

select 
case 
when a.catagory='Purchase Account' then 
l.name 
end as PurchaseAccount, 
case 
when a.catagory = 'Sales Account' then 
l.name 
end as SalesAccount 
from ledger l join accountmast a 
on l.companyID=a.companyID 
and l.name = a.accname 
where l.companyID=102 
and a.catagory='Purchase Account' or a.catagory='Sales Account' 
group by l.name,a.catagory 

結果是:

PurchaseAccount  SaleAccount 
PURCHASE ACCOUNT NULL 
NULL    SALES ACCOUNT 

,但我想結果一樣:

PurchaseAccount  SaleAccount 
PURCHASE ACCOUNT SALES ACCOUNT 

如何做到這一點?

回答

1

刪除您GROUP BY條款:

select 
    max(case when a.catagory = 'Purchase Account' then l.name end) as PurchaseAccount, 
    max(case when a.catagory = 'Sales Account' then l.name end) as SalesAccount 
from ledger l 
join accountmast a 
on l.companyID = a.companyID and l.name = a.accname 
where l.companyID=102 and a.catagory IN ('Purchase Account', 'Sales Account') 
+0

很抱歉,但它沒有區別它的顯示結果,因爲我不不會。它顯示了我上面說的結果。 – mahesh

+0

你錯過了一件事,那就是忘記刪除由l.name組的組,你已經通過max運行它否則你的代碼太好所以刪除它,然後我會接受你的答案是正確的 – mahesh

+0

你有任何關於如何在相同條件下添加購買金額。 – mahesh