首页 > 解决方案 > 如何根据 ID 和名称对总支出进行分组

问题描述

我有一张桌子

patientId  | Units | Amount | PatientName
1234       |   1   |   20   |lisa
1111       |   5   |   10   |john
1234       |   10  |   200  |lisa
345        |  2     |   30  | xyz

我想在一列中获取 ID,然后是患者姓名,然后是他在不同项目上花费的总金额,

请注意,我通过使用 ID 作为键对 2 个表进行连接,在上面的列中获得了患者姓名

我这样做是为了得到这张桌子

select t1.*,t2.name from table1 as t1 inner join table2 as t2
on t1.id = t2.id

然后添加我正在尝试使用该group by子句,但这给出了一个错误

请注意,我不能在此使用临时表,只需要使用子查询来执行此操作,该怎么做?

标签: sqlsql-server

解决方案


你在找group by吗?

select t1.patientid, t2.patientname, sum(t1.amount)
from table1 t1 join
     table2 t2
     on t1.id = t2.id
group by t1.patientid, t2.patientname;

推荐阅读