ID上的组和来自不同表的总和(总共3个表)

时间:2012-03-24 14:28:11

标签: sql sql-server group-by sum multiple-tables

我有三张桌子,

Name - columns 
Custpackingslipjour(table 1) - (deliverydate, dateclosed,, salesid)
Inventrans (Table 2) -  (itemid, datephysical, transrefid)
Salesline (Table 3) -  (lineamount, itemid, salesid

我需要的是一个包含所有三个表的单个表,但是没有多个相同销售额的冗余信息,以及总金额(salesline.lineamount)以及我可以根据deliverydate和关闭日期消除结果的情况,与datephysical一起,最初我有这个。

SELECT     TOP (10) dbo.AX_CUSTPACKINGSLIPJOUR.DELIVERYDATE,
dbo.AX_SALESLINE.LINEAMOUNT, dbo.AX_INVENTTRANS.DATEPHYSICAL, 
dbo.AX_INVENTTRANS.COSTAMOUNTPOSTED, dbo.AX_INVENTTRANS.ITEMID, 
dbo.AX_INVENTTRANS.TRANSREFID, dbo.AX_CUSTPACKINGSLIPJOUR.SALESID
FROM         dbo.AX_CUSTPACKINGSLIPJOUR
     INNER JOIN
dbo.AX_SALESLINE ON dbo.AX_CUSTPACKINGSLIPJOUR.SALESID = dbo.AX_SALESLINE.SALESID 
     INNER JOIN
     dbo.AX_INVENTTRANS ON dbo.AX_SALESLINE.ITEMID = dbo.AX_INVENTTRANS.ITEMID

但由于salesid和itemid之间固有的一对多关系,它产生了一个包含许多相同行的表。

所以我想我会将与每个salesid相关联的项目的价值总和分组,因为这就是我所追求的。

基于此处的其他一些帖子,我尝试将salesline中的lineamount总和合并到salesid上,但是在运行5分钟后,它似乎不是一个好的解决方案,我认为我有权利想法,但我做错了。

select top 10 s.SALESID,
    SUM(sp.LINEAMOUNT) as 'TotalLineamount'
from AX_CUSTPACKINGSLIPJOUR as s
right outer join AX_SALESLINE as sp on s.SALESID=sp.SALESID 
left outer join AX_INVENTTRANS as p on sp.ITEMID=p.ITEMID
where s.SALESID is not null
group by s.SALESID,sp.LINEAMOUNT

非常感谢任何帮助,如果我想做的事情不清楚,我会跟进任何问题或评论。

编辑:遵循@coltech的建议,并尝试使用sales上的distinct,但没有工作,但它已经过测试。我在前十名之后插入了distinct(salesid)

编辑:根据Gavins的建议,我改为

select top 10 cp.SALESID,
SUM(sl.LINEAMOUNT) as 'TotalLineamount'
from AX_CUSTPACKINGSLIPJOUR as cp
right outer join AX_SALESLINE as sl on cp.SALESID=sl.SALESID 
left outer join AX_INVENTTRANS as it on sl.ITEMID=it.ITEMID
where cp.SALESID is not null
group by cp.SALESID

我还更改了表的前缀以更好地匹配表名。但是,如果我想要包含更多列,则可以正常工作。     sl.LINEAMOUNT,it.DATEPHYSICAL,it.COSTAMOUNTPOSTED,it.ITEMID,it.TRANSREFID和cp.SALESID

然后我将不得不将这些包括在这个组中。

select top 10 cp.SALESID,
SUM(sl.LINEAMOUNT) as 'TotalLineamount',
cp.DELIVERYDATE,
sl.LINEAMOUNT, it.DATEPHYSICAL, 
it.COSTAMOUNTPOSTED, it.ITEMID, 
it.TRANSREFID, cp.SALESID
from AX_CUSTPACKINGSLIPJOUR as cp
right outer join AX_SALESLINE as sl on cp.SALESID=sl.SALESID 
left outer join AX_INVENTTRANS as it on sl.ITEMID=it.ITEMID
where cp.SALESID is not null
group by cp.SALESID, cp.DELIVERYDATE,sl.LINEAMOUNT, it.DATEPHYSICAL, it.COSTAMOUNTPOSTED, it.ITEMID, it.transrefid

但是,这似乎会导致查询运行很长时间,运行时间接近25分钟。有没有办法加快速度?或者我只是错误地解决了这个问题?

1 个答案:

答案 0 :(得分:2)

我认为你很好,除非你不应该总结你想要分组的列,所以只需这样做:

select top 10 s.SALESID,
    SUM(sp.LINEAMOUNT) as 'TotalLineamount'
from AX_CUSTPACKINGSLIPJOUR as s
right outer join AX_SALESLINE as sp on s.SALESID=sp.SALESID 
left outer join AX_INVENTTRANS as p on sp.ITEMID=p.ITEMID
where s.SALESID is not null
group by s.SALESID