访问数据库的复杂查询设计

时间:2013-10-07 10:20:52

标签: c# ms-access-2007

我有以下三个表(仅出于表示原因显示必填字段)。

表'product_master'

ID  ProductName
1   Jens
2   T-shirt
3   Shirt
4   Cap

表'账单'

ID  Invoiceno   Date
1   INV001       19/9/2013
2   INV002       20/9/2013
3   INV003       20/9/2013

表'billDetails'

ID  Invoiceno   Productid       Qyt
1   INV001             1             2
2   INV001             2             3
3   INV001             4             1
4   INV002             2             1
5   INV002             3             2
6   INV003             1             3
7   INV003             4             2

我想要的输出

SalesReport(任意两个日期之间的每日)

ProductName TotalSales  Date
Jens                2         19/9/2013
T-shirt             4         19/9/2013
Shirt               2         19/9/2013
Cap                 1         19/9/2013
Jens                3         20/9/2013
T-shirt             0         20/9/2013
Shirt               0         20/9/2013
Cap                 2         20/9/2013

此查询不起作用:

        SELECT
        [PM.product_master], [SUM(IM.Qyt)], [BM.Date] FROM
        [product_master] AS PM
        INNER JOIN 
        [billDetails] AS IM
        ON
        [PM.sno] = [IM.prod_sno]
        INNER JOIN
        [bill] AS BM
        ON
        [IM.Invoiceno] = [BM.Invoiceno]

2 个答案:

答案 0 :(得分:3)

  

现在我想要这样的输出SalesReport(任意两个之间的每日   日期)

为了计算每天的总销售额,您必须按日期group数据。要指定期间,您必须使用having子句。

SELECT product_master.ProductName, Sum(billDetails.Qty) AS SumOfQty, bill.Dated
FROM bill 
INNER JOIN (
product_master INNER JOIN billDetails ON product_master.ID = billDetails.ProductId
) ON bill.InvoiceNo = billDetails.InvoiceNo
GROUP BY product_master.ProductName, bill.Dated
HAVING bill.Dated Between #9/19/2013# And #9/20/2013#
ORDER BY bill.Dated, product_master.ProductName

答案 1 :(得分:1)

尝试此查询

select product_master.ProductName
       ,SUM(billDetails.Qyt) as TotalSales
       ,bill.Date 
from billDetails
inner join bill on billDetails.Invoiceno = bill.Invoiceno 
inner join product_master on product_master.Id = billDetails.Productid