一列分区上的Sql空值

时间:2012-06-05 07:39:11

标签: sql sql-server-2005

我只是在这个Sql Transact后面浪费了两到三个Hourse,并且对Null Value Skip感到困惑。

我有两张如下表:

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 个答案:

答案 0 :(得分: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')