需要按名称分组

时间:2018-08-03 14:43:02

标签: sql

我有一个表,其中包含Id,Name,Program,Amount1,Amount2列。

/* Create a table called NAMES */
CREATE TABLE NAMES(Id integer PRIMARY KEY, Name text, Program char, Amount1 integer, Amount2 integer);

/* Create few records in this table */
INSERT INTO NAMES VALUES(1,'Abc','A',10  ,null);
INSERT INTO NAMES VALUES(2,'Abc','B',null,20);
INSERT INTO NAMES VALUES(3,'Def','A',30  ,null);
INSERT INTO NAMES VALUES(4,'Def','B',null,40);
INSERT INTO NAMES VALUES(5,'Pqr','A',50  ,null);
INSERT INTO NAMES VALUES(6,'Pqr','B',null,60);
INSERT INTO NAMES VALUES(7,'Xyz','A',70  ,null);
INSERT INTO NAMES VALUES(8,'Xyz','B',null,80);
COMMIT;

/* Display all the records from the table */
SELECT Name,Amount1,Amount2 FROM NAMES
group by Name;

如下所示,请帮助按名称将输出和名称Amount1,Amount2分组。 HTML表格

Name    Amount1 Amount2
Abc     10      20
Def     30      40
Pqr     50      60
Xyz     70      80

2 个答案:

答案 0 :(得分:1)

您可以使用聚合函数,例如:max

SELECT Name,max(Amount1),max(Amount2) 
FROM NAMES
group by Name;

或GoranKutlaca sum()的建议

SELECT Name,sum(Amount1),sum(Amount2) 
FROM NAMES
group by Name;

答案 1 :(得分:1)

这是一个简单的分组依据,具有汇总功能。

SELECT Name,SUM(Amount1),SUM(Amount2) 
FROM NAMES 
GROUP BY Name;