复杂分组查询

时间:2014-12-03 12:30:02

标签: sql group-by aggregate-functions

下面是我的sql查询,我已经放了一些MAX(table_name),因为当使用group by时我不能只放表名。如果我输入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

2 个答案:

答案 0 :(得分:0)

“另外,那些MAX(table_name)都是相同的值,没有什么不同,我只需要打印它。”

为什么不能只将它们添加到选择列表和组中呢?

这个不起作用?

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

答案 1 :(得分:0)

您不必添加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