Sql 需要按名称分组
我有一个表,其中有Id、Name、Program、Amount1、Amount2列Sql 需要按名称分组,sql,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
/* 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
您可以使用聚合函数,例如:max
SELECT Name,max(Amount1),max(Amount2)
FROM NAMES
group by Name;
或者按照GoranKutlaca sum()的建议
这是一个简单的group by,带有聚合函数
SELECT Name,SUM(Amount1),SUM(Amount2)
FROM NAMES
GROUP BY Name;
简单地
SUM(column)
当您“按名称分组”时,每个名称都会有一条记录。您希望其中的Amount1和Amount2的单个值是多少?我相信Sum()比Max()更符合数据的精神,正如对问题的评论所暗示的。可能这两个程序都指定了某个数量。@GoranKutlaca。。asnwer已更新。我也同意你的建议
SELECT Name,SUM(Amount1),SUM(Amount2)
FROM NAMES
GROUP BY Name;