按一个不同的另一列分组SQL

时间:2019-06-27 12:18:43

标签: sql sql-server

我有一个如下表:

CREATE TABLE mine_1 ([name] VARCHAR(255) , [BRAND] VARCHAR(255) , [RX] int)

INSERT INTO mine_1
    ([name],[BRAND], [RX])
VALUES
    ('2017','ABC',5),
    ('2017','def',15),
    ('2018','efg',8),
    ('2018','hij',9); 

SQLfiddle demo

我想按nameBrandsum(Rx)进行分组,并且输出应如下所示,

('2017','ABC',20)
('2017','def',20)
('2018','efg',17)
('2018','hij',17)

1 个答案:

答案 0 :(得分:2)

将查询加入表:

select m.name, m.BRAND, g.RX 
FROM mine_1 m inner join (
  select name, SUM(RX) RX  
  FROM mine_1 
  group by name
) g on g.name = m.name