按两个或更多条目分组为单个记录

时间:2018-12-17 19:40:27

标签: sql sql-server tsql group-by

我正在努力提出一种优雅的方式来进行分组。这是一些示例数据… 我无法提出(未完全弄乱的东西)

Create table tax(Prod_ID varchar(15), Authority varchar(15), Rate     decimal(15,10)) 
insert into tax(prod_id, Authority, rate) 
VALUES
('UNL',       'TX',  0.20000000000000000000000), 
('UNL',       'USA', 0.18300000000000000000000), 
('UNL',       'USA', 0.00100000000000000000000), 
('UNL',       'TX',  0.00099285714285714285714), 
('UNL',       'AL',  0.18000000000000000000000)

任何具有“美国”权限的条目都需要添加到每个州,例如TX,AL,FL等州。 因此,根据以上数据,我想得出的结果如下……

Prod_ID, Authority, Sum(Rate)
UNL, TX, 0.38499285714285714285714
UNL, AL, 0.36400000000000000000000

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找类似的东西

select t.prod_id 'Prod_ID', t.authority 'Authority',
        (SUM(Rate) +(SELECT SUM(RATE) FROM tax t where Authority = 'USA'))  as 'Sum(Rate)'
from tax t 
WHERE Authority <> 'USA'
GROUP BY Prod_ID,Authority 

答案 1 :(得分:0)

嗯。 。 。我认为JOIN就足够了:

with t as (
      select t.prod_id, t.authority, sum(t.rate) as rate
      from tax t
      group by t.prod_id, t.authority
     )   
select t.prod_id, t.authority,
       (t.rate + coalesce(tusa.rate, 0)) as total_rate
from t left join
     t tusa
     on t.prod_id = tusa.prod_id and tusa.authority = 'USA'
where t.authority <> 'USA'