[英]Self-Join SQL statement w/calculated data
I have a table with the following data: 我有一个包含以下数据的表:
id date name schedulenum paymentamt
1 12/2/2014 AB 077LR10 100
2 12/2/2014 AN 077LR10 200
3 12/2/2014 CD 077LR10 300
4 3/10/2015 AN 083LR12 200
5 3/10/2015 WC 083LR12 500
6 5/20/2015 AB 105LR20 200
7 5/20/2015 CD 105LR20 150
8 5/20/2015 RH 105LR20 150
9 5/20/2015 RG 105LR20 400
And I would like to write a query that would bring back the following results: 我想编写一个查询,将带回以下结果:
schedulenum paymentamt
077LR10 600
083LR12 700
105LR20 900
Basically I need to create a SQL statement that selects data from Table A
that will result in 2 columns. 基本上,我需要创建一个SQL语句,该语句从Table A
中选择数据,这将导致2列。 The first column would be a unique schedule number (ie, 'schedulenum'
- there are multiple rows with the same schedulenum
) and a total payment amount ( 'paymentamt'
) per schedulenum
(each row will have a different 'paymentamt'
). 第一列将是唯一的时间表编号(即'schedulenum'
有多个具有相同schedulenum
行),并且每个schedulenum
的总付款金额( 'paymentamt'
)(每行将具有不同的'paymentamt'
)。 I think this would require a self-join but not sure how to do it. 我认为这需要自我加入,但不确定如何去做。
Use a group by when getting sums from one table. 从一个表中获取总和时使用分组依据。
select schedulenum, sum(payment) from mytable
where schedulenum = x
group by schhedulenum
... ...
select schedulenum, sum(payment) from mytable
group by schhedulenum
order by schedulenum
No self-join needed at all. 完全不需要自我加入。 What you want is the 'group by' keyword and aggregate functions. 您想要的是“ group by”关键字和聚合函数。
SELECT schedulenum, sum(paymentamt)
FROM [TABLE]
GROUP BY schedulenum;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.