加入表+ SUM& GROUP BY功能

时间:2017-05-02 12:30:25

标签: sql

我正在努力与SUM和GROUP BY功能一起连接表。下面的查询工作正常:

select ID, sum(amount)
from table1
group by ID
having sum(amount) between 1000 and 10000

由于table1仅包含客户ID,我还需要连接表CUSTOMERS,其中包含客户名称(列NAME)。以下查询将不再适用于我:

select ID, name, sum(amount)
from table1
left join customers on table1.ID = customers.ID2
group by ID
having sum(amount) between 1000 and 10000

忽略SUMGROUP BY功能会“解决”问题,因为结果中也会显示列NAME,但我仍需要根据ID对AMOUNT进行求和。在这种情况下,我应该如何加入另一个表来同时从表CUSTOMERS中显示字段NAME?

  

SELECT列表中的列NAME或表达式无效'

目前是错误消息。

3 个答案:

答案 0 :(得分:0)

它必须位于group by

select t1.ID, c.name, sum(t1.amount)
from table1 t1 left join
     customers c
     on t1.ID = c.ID2
group by t1.ID, c.name;

请注意表别名的使用。

答案 1 :(得分:0)

添加"名称"在分组条款中

select table1.ID, customers.name, sum(table1.amount) amount
from table1,customers on table1.ID = customers.ID2
group by table1.ID,customers.name

答案 2 :(得分:0)

试试吧

from django import forms

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=100)
    file = forms.FileField()

或没有取决于您的要求