2016-08-04 31 views
1

第一个表是我的输入,并且期望输出像第二个表一样使用左连接。 这是表数据使用左连接期望输出未输出

declare @table table 
(customer_id int, 
indicator bit, 
salary numeric(22,6) 
,netresult numeric(22,6)) 

INSERT INTO @table (
    customer_id 
    ,indicator 
    ,salary 
    ) 
VALUES 
(1,1,2000), 
(1,1,3000), 
(2,1,1000), 
(1,0,500), 
(1,1,5000), 
(2,1,2000), 
(2,0,100) 

select * from @table order by customer_id,indicator desc 

我试图在它下面的工作方法。有没有更好的选择?

SELECT a.customer_id 
    ,a.indicator 
    ,a.salary 
    ,netresult=p_salary-(2*n_salary) 
FROM (
    SELECT customer_id 
     ,indicator 
     ,salary 
     ,sum(salary) OVER (PARTITION BY customer_id) p_salary 
    FROM @table 
    ) a 
LEFT JOIN (
    SELECT customer_id 
     ,indicator 
     ,salary 
     ,sum(salary) OVER (PARTITION BY customer_id) n_salary 
    FROM @table 
    WHERE indicator = 0 
    ) b ON a.customer_id = b.customer_id 
    order by customer_id,indicator desc 

期望输出

enter image description here

回答

3

我想你想要这样的:

select t.customer_id, t.indicator, 
     sum(case when indicator = 1 then salary else - salary end) over (partition by customer_id) as netresult 
form @table t; 

没有连接是必要的。

1

与数学

select t.customer_id, t.indicator, t.salary 
    , sum(((t.indicator * 2) -1) * salary) over (partition by customer_id) as netresult 
from @table t;