使用T-SQL在JOIN中计算列

时间:2013-04-18 14:20:26

标签: sql sql-server tsql group-by aggregate-functions

我想显示一个人申请总量的总和。

我试过这个:

SELECT DISTINCT custID, firstName, AppID, AppDate, Amount
FROM CustTable
JOIN AppTable ON custID = AppID

我每个客户都有很多行,并且希望总结每个客户的总申请金额

目前我看到这样的事情:

1 | Jon | APP_1 | 200 
1 | Jon | APP_2 | 200
1 | Jon | APP_3 | 200
1 | Jon | APP_4 | 200

但我想(理想情况下是日期范围):

1 | Jon | APP_1 | 800

3 个答案:

答案 0 :(得分:1)

你可以这样做:

select custID, firstName, sum(Amount)
FROM CustTable
JOIN AppTable
ON custID = AppID
group by custID, firstName

将返回此信息:

1 | Jon | 800

此外,您可以使用以下日期范围:

select custID, firstName, sum(Amount), 
       min(AppDate) firstDate, max(AppDate) lastDate, 
FROM CustTable
JOIN AppTable
ON custID = AppID
group by custID, firstName

将返回如下内容:

1 | Jon | 800 | 2013-01-01 | 2013-01-28

答案 1 :(得分:0)

根据您表格中的区别,我假设您希望按照AppDate对其进行分组:

SELECT custID, firstName, AppID, AppDate, SUM(Amount) AS Amount 
FROM CustTable
JOIN AppTable
ON custID = AppID

GROUP BY custID, firstName, AppID, AppDate

您的结果列表没有AppDate,因此当AppDate不对这些值进行分组时,您必须在没有AppDate的情况下执行此操作:

SELECT custID, firstName, AppID, SUM(Amount) AS Amount 
FROM CustTable
JOIN AppTable
ON custID = AppID

GROUP BY custID, firstName, AppID

如果你想要

1 | Jon | APP_1 | 800 

在您的示例中,使用按字母顺序排列的第一个应用ID作为名称,它就像这样

SELECT custID, firstName, MIN(AppID) AS AppID, SUM(Amount) AS Amount 
FROM CustTable
JOIN AppTable
ON custID = AppID

GROUP BY custID, firstName

但说实话,在结果中使用APP_1并没有多大意义。

答案 2 :(得分:0)

这是一个基本的group by查询:

SELECT custID, COUNT(*) as Num, SUM(Amount) as TotalAmount
FROM CustTable JOIN AppTable
     ON custID = AppID
group by custId

但是,我没有看到第三列“APP1”在输出中做了什么。