SQL 查询通过使用不同的特征在一列中添加值来插入新列

SQL query to insert a new column by adding the values in one column using distinct features

我有 table 三列 (a,b,c),我需要创建一个新列 'd',利用列 a 和 b 的不同特征。

a  b  c
1  p  2
1  p  3 
2  q  4
1  q  2
2  r  4
2  r  2
1  p  2 

我需要如下答案,其中 d 是 a 和 b 的唯一列的总和

a b c d
1 p 2 7
1 p 3 7
2 q 4 4
1 q 2 2
2 r 4 6
2 r 2 6
1 p 2 7

d 列的结果是,

对于不同的(a 和 b), 然后,添加 c 的值。 然后在 d 列中插入值(匹配不同的值)

使用 case when 并在生成的值不变的情况下创建另一列

 select a,b,c, case when a=1  and b='p'  then 7
    when a=2 and b='q' then 4
    when a=2 and b='r' then 6
    when a=1 and b='q' then 2 else '' end as d from
    your_table

但在我看来你需要 a,b 的组总和作为第 4 列 d ,所以 你可以像下面那样做

select t1.a,t1.b,t1.c,t2.d from yourtable t1
inner join
(select a,b ,sum(c) as d from your table group by a,b) as t2
on t1.a=t2.a and t1.b=t2.b

你可以尝试在子查询中使用SUMgroup byab列,然后自己join

TestDLL

create table t(
   a int,
   b varchar(5),
   c int
);

insert into t values (1,'p',2);
insert into t values (1,'p',3);
insert into t values (2,'q',4);
insert into t values (1,'q',2);
insert into t values (2,'r',4);
insert into t values (2,'r',2);
insert into t values (1,'p',2);

查询

SELECT t1.*,t2.d 
FROM T t1 INNER JOIN (
    SELECT a,b,SUM(c) d
    FROM T
    GROUP BY a,b
) t2 on t1.a = t2.a and t1.b=t2.b 

[结果]:

| a | b | c | d |
|---|---|---|---|
| 1 | p | 2 | 7 |
| 1 | p | 3 | 7 |
| 2 | q | 4 | 4 |
| 1 | q | 2 | 2 |
| 2 | r | 4 | 6 |
| 2 | r | 2 | 6 |
| 1 | p | 2 | 7 |

sqlfiddle

如果支持 SUM 的 window 函数

select a, b, c, sum(c) over (partition by a, b) as d
from yourtable