在Access中使用带有多个表的聚合函数

时间:2013-05-19 09:20:35

标签: mysql sql ms-access access-vba

我有四个表项,Customer,Invoice_summary,Invoice_details。在这里,我想加入这四个表,并获得特定item_code和特定日期范围的Sum(Invoice_details.Item_quntity)和Sum(Invoice_details.Price)。主要栏目如下:

Invoice_summary :Inv_num,Inv_date,Cus_id,Total 
Items           :Item_code,Item_name,Unit_price
Invoice_details :Inv_num,Item_code,Item_qty,Price
Customers       :Cus_id,Cus_name,Route

这是我目前所拥有的。这回复了多行(整个项目名称)我只需要一个特定的项目代码。可以有人解释我出错的地方。

SELECT Invoice_Table.Item_Code, Items.Item_Name, 
       (Select sum(Invoice_Table.Item_Quntity)  from (Invoice_Table INNER JOIN Invoice ON Invoice_Table.Inv_Num = Invoice.Inv_Num) where ((Invoice_Table.Item_Code=[?]) And Invoice.inv_date Between #3/4/2013# And #6/4/2013#) group BY Invoice_Table.Item_Code) AS Quntity, 
       (Select sum(Invoice_Table.Price)  from (Invoice_Table INNER JOIN Invoice ON Invoice_Table.Inv_Num = Invoice.Inv_Num) where ((Invoice_Table.Item_Code=[?]) And Invoice.inv_date Between #3/4/2013# And #6/4/2013#) group BY Invoice_Table.Item_Code) AS Price 
FROM Invoice_Table 
INNER JOIN Items ON Invoice_Table.Item_Code = Items.Item_Code 
GROUP BY Invoice_Table.Item_Code, Items.Item_Name;

2 个答案:

答案 0 :(得分:0)

试试这个..

Select ID.Item_qty,ID.Price,I.Item_code from Invoice_summary IS 
INNER JOIN Invoice_details ID ON ID.Inv_num=IS.Inv_num
INNER JOIN Customers C ON C.Cus_id=IS.Inv_num
INNER JOIN Items I ON I.Item_code=ID.Item_code

答案 1 :(得分:0)

您对此感兴趣的金额应由此查询提供。

select Inv_num, Item_code, 
       sum(Item_qty) item_code_qty, 
       sum(Price) item_code_price
from invoice_details
group by Inv_num, Item_code

看起来应该在发票摘要表中找到日期范围。看起来Invoice_summary和Invoice_details应该可以在Inv_num上连接。

select inv_s.Inv_num, inv_s.Inv_date, inv_s.Cus_id, inv_s.Total,
       inv_t.item_code_qty, inv_t.item_code_price
from Invoice_summary inv_s
inner join (select Inv_num, Item_code, 
                   sum(Item_qty) item_code_qty, 
                   sum(Price) item_code_price
            from invoice_details
            group by Inv_num, Item_code
            ) inv_t
        on inv_s.Inv_num = inv_t.Inv_num
where inv_s.Inv_date between ? and ?;

要解决这个问题,请将其他两个表连接到其键上,并将其中的一些列添加到SELECT子句中。

select inv_s.Inv_num, inv_s.Inv_date, inv_s.Cus_id, cus.Cus_name, inv_s.Total,
       inv_t.item_code_qty, inv_t.item_code_price,
       items.name
from Invoice_summary inv_s
inner join (select Inv_num, Item_code, 
                   sum(Item_qty) item_code_qty, 
                   sum(Price) item_code_price
            from invoice_details
            group by Inv_num, Item_code
            ) inv_t
        on inv_s.Inv_num = inv_t.Inv_num
inner join items on items.Item_code = inv_t.Item_code
inner join Customers cus on cus.Cus_id = inv_s.Cus_id
where inv_s.Inv_date between ? and ?;
相关问题