当同一表中其他列的值为1时,将列的值返回null或为空

时间:2014-07-03 17:57:21

标签: sql sql-server sql-server-2012-express

我正在研究一个SQL查询,它有一些连接会产生一定数量的行和列。我试图以这样的方式返回结果:当一行中特定列的值为1时,同一行但不同列中的某个其他值应返回为空值。

我在SQL Server 2012中的SQL查询如下

select a.id,a. Date, c.companyname as 'Active Company', h.employee_fullname as ‘Client',j.displayname as 'Seller Employee', d.companyName as 'CounterParty Company',g.broker_fullname as 'Buyer Trader', a.transactiontype
from confirmations a with (nolock)
left join company c with (nolock) on c.company_id = a.activecompany
left join company d with (nolock) on d.company_id = a.counterCompany
left join bprod e with (nolock) on e.id = a.productID
left join btype f with (nolock) on  f.id = a.quantitytypeid
left join companybroker g with (nolock) on g.companybroker_id = a.counter
left join companybroker h with (nolock) on h.companybroker_id = a.active
left join users i with (nolock) on i.id = a.buyemp
left join users j with (nolock) on j.id = a.sellemp
Where JoinDate > '2011-06-04 00:00:00' 
and a.disabled = 0 
order by dealid

以上查询返回以下结果

Id Active Company Client Seller Employee CounterPartyCompany Buyer Trader Transaction Type
1  ABC             XYZ      PQR             CHEV                 John           0
2  ABC2            2XYZ    2PQR            2CHEV                 John11         0
3  3ABC            3XYZ     3PQR           3CHEV                 John12         1
4  3ABC            3XYZ     AAA              CCC                 John12         1

一切看起来都很好,但是当CounterPartyCompany为1时,我试图将Transaction Type作为空的返回

 Id Active Company Client Seller Employee CounterPartyCompany Buyer Trader Transaction Type
    1  ABC             XYZ      PQR             CHEV                 John           0
    2  ABC2            2XYZ    2PQR            2CHEV                 John11         0
    3  3ABC            3XYZ     3PQR                                 John12         1
    4  3ABC            3XYZ     AAA                                  John12         1

我可以知道更好的解决方法吗

1 个答案:

答案 0 :(得分:2)

完美用于案例陈述:

select a.id, a.Date, c.companyname as 'Active Company', 
h.employee_fullname as 'Client', j.displayname as 'Seller Employee', 
case when a.transactionType =1 then null
else d.companyName end as 'CounterPartyCompany',
g.broker_fullname as 'Buyer Trader', a.transactiontype
from confirmations a with (nolock)
left join company c with (nolock) on c.company_id = a.activecompany
left join company d with (nolock) on d.company_id = a.counterCompany
left join bprod e with (nolock) on e.id = a.productID
left join btype f with (nolock) on  f.id = a.quantitytypeid
left join companybroker g with (nolock) on g.companybroker_id = a.counter
left join companybroker h with (nolock) on h.companybroker_id = a.active
left join users i with (nolock) on i.id = a.buyemp
left join users j with (nolock) on j.id = a.sellemp
Where JoinDate > '2011-06-04 00:00:00' 
and a.disabled = 0 
order by dealid

这假设只有1应为null / empty。所有其他出现的transactionType都将导致显示d.companyName。