Sql 复杂分组查询

Sql 复杂分组查询,sql,group-by,aggregate-functions,Sql,Group By,Aggregate Functions,下面是我的sql查询,我放了一些MAX(表名),因为当使用GROUPBY时,我不能只放表名。如果我输入MAX,当有varchar值时执行需要时间,请为varchar提供好的聚合函数,而不是MAX 而且,那些MAX(table_name)都是相同的值,没有区别,我只需要打印它 select distinct t1.PartyName as Customer_Name, SUM(t2.Amount) as Bill_Amount, MAX(t2.VoucherNumbe

下面是我的sql查询,我放了一些MAX(表名),因为当使用GROUPBY时,我不能只放表名。如果我输入MAX,当有varchar值时执行需要时间,请为varchar提供好的聚合函数,而不是MAX

而且,那些MAX(table_name)都是相同的值,没有区别,我只需要打印它

select distinct 
    t1.PartyName as Customer_Name, 
    SUM(t2.Amount) as Bill_Amount, 
    MAX(t2.VoucherNumber) as Invoice_Number, 
    SUM(i.Weight * t2.Aqty) as Weight, 
    CEILING(SUM(i.CBM * (t2.Aqty/c.Nos))) as CBM, 
    MAX(p.Channel) as Type, 
    MAX(p.RouteNo) as RouteNo, 
    MAX(t1.Adress3) as City
from 
    Item i, 
    Party p, 
    Tran1 t1, 
    VTran2 t2, 
    Cases c
Where 
    t1.VoucherNumber=t2.VoucherNumber and 
    t2.ItemName=i.Itemname and 
    p.PartyName=t1.PartyName and 
    t2.ItemName=c.ItemName and 
    p.RouteNo='" + routeNo1comboBox.Text + "' and 
    t1.LoadingStatus IS NULL and 
    t1.Date BETWEEN '" + startDate + "' and '" + endDate + "' 

GROUP BY t1.PartyName
“而且,那些MAX(表名称)都是相同的值,没有区别,我只需要打印它。”

为什么不能将它们添加到“选择”列表和“分组依据”列表中

这个不行吗

select distinct 
    t1.PartyName as Customer_Name, 
    SUM(t2.Amount) as Bill_Amount, 
    t2.VoucherNumber as Invoice_Number, 
    SUM(i.Weight * t2.Aqty) as Weight, 
    CEILING(SUM(i.CBM * (t2.Aqty/c.Nos))) as CBM, 
    p.Channel as Type, 
    p.RouteNo as RouteNo, 
    t1.Adress3 as City
from Item i, Party p, Tran1 t1, VTran2 t2, Cases c
Where t1.VoucherNumber=t2.VoucherNumber 
and t2.ItemName=i.Itemname 
and p.PartyName=t1.PartyName 
and t2.ItemName=c.ItemName 
and p.RouteNo=''' + routeNo1comboBox.Text + ''' 
and t1.LoadingStatus IS NULL 
and t1.Date BETWEEN ''' + startDate + ''' and ''' + endDate + ''' 
GROUP BY t1.PartyName, cs,t2.VoucherNumber,p.Channel,p.RouteNo,t1.Adress3

您不必添加
distinct
,因为您已经按照t1.PartyName、t2.VoucherNumber、p.Channel、p.RouteNo、t1.Adress3进行分组

select 
    t1.PartyName as Customer_Name, 
    SUM(t2.Amount) as Bill_Amount, 
    t2.VoucherNumber as Invoice_Number, 
    SUM(i.Weight * t2.Aqty) as Weight, 
    CEILING(SUM(i.CBM * (t2.Aqty/c.Nos))) as CBM, 
    p.Channel as Type, 
    p.RouteNo as RouteNo, 
    t1.Adress3 as City
from Item i, Party p, Tran1 t1, VTran2 t2, Cases c
Where t1.VoucherNumber=t2.VoucherNumber 
and t2.ItemName=i.Itemname 
and p.PartyName=t1.PartyName 
and t2.ItemName=c.ItemName 
and p.RouteNo=''' + routeNo1comboBox.Text + ''' 
and t1.LoadingStatus IS NULL 
and t1.Date BETWEEN ''' + startDate + ''' and ''' + endDate + ''' 
GROUP BY t1.PartyName, cs,t2.VoucherNumber,p.Channel,p.RouteNo,t1.Adress3

您的
join
条件可能是错误的。将查询修复为使用propoer
join
语法,这可能会解决您的问题。如果所有记录的
table\u name
都是相同的,那么您为什么需要对其执行聚合函数,只需将其包含在
SELECT
列表中即可。您好,Gordon,谢谢您的回复,你能为我的例子提供一些小的修改吗?在此之后,我可以很容易地捕捉。非常感谢Alexandru Aliu为您提供简单易用的修改解决方案。