如何使用(子)总计为复杂报表编写查询?

时间:2016-03-09 01:12:52

标签: sql sqlite

我正在尝试编写SQLite代码,以下面列出的形式打印报告。一旦我生成了查询,我将编写一个简单的Python脚本,以与下面相同的方式组织信息。我遇到的麻烦是确定查询。

我的数据库方案如下:

Customer (customerID, lastName, firstName, age, gender, street, city, state, favorites, lastVisit)

LineItem (receiptID, lineNum, productID) Product (productID, flavor, kind, price)

ProductXSale(productID, saleID)

Rating (customerID, productID, score, comment)

Receipt (receiptID, purchaseDate, customerID)

Sale (saleID, startDate, endDate, percentOff)

我认为在构建查询时我们不需要评级或客户表。

对我来说,困难的部分是确定某一天的产品X的数量。为了计算这一点,我们需要检查日期Y上的每张收据,并计算X在每张收据上出现的次数。

另一个问题是,如果某个时间点发生了销售。因此,如果产品X开始销售,那么我们需要以降价报告。

当然,每列的收入是通过将销售产品的数量乘以其价格来计算的(检查是否有销售)。

模型报告:

SALES REPORT FOR year-month

Product.id  Product.flavor  Product.kind  Product.price

    SALE DATE            NBR SOLD       INCOME
    date-of-purchase     number-sold    total-amount
    date-of-purchase     number-sold    total-amount
    date-of-purchase     number-sold    total-amount
    ⋮
    date-of-purchase     number-sold    total-amount

             TOTALS:  total-nbr-sold     total-total

Product.id  Product.flavor  Product.kind  Product.price

    SALE DATE            NBR SOLD       INCOME
    date-of-purchase     number-sold    total-amount
    date-of-purchase     number-sold    total-amount
    date-of-purchase     number-sold    total-amount
    ⋮
    date-of-purchase     number-sold    total-amount

             TOTALS:  total-nbr-sold     total-total

⋮

    GRAND TOTALS:            1234          999.99

我已经尝试了几个查询,而我只是专注于获取每天销售的每件商品的数量。这是我到目前为止所做的:

SELECT P.id, P.flavor, P.kind, P.price, R.purchasedate
FROM Product AS P, Receipt AS R
GROUP BY R.purchasedate, P.id
ORDER BY P.id, DATE(R.purchasedate);
This produces something like:

id          flavor        kind      price       purchasedate
20-BC-C-10  Chocolate     Cake      8.95        2015-10-01
20-BC-C-10  Chocolate     Cake      8.95        2015-10-02
20-BC-C-10  Chocolate     Cake      8.95        2015-10-03
...

基本上,这个查询只列出了每天按项目分组的一项。

链接到数据库:https://onedrive.live.com/redir?resid=6F5AA23EB67D4C49!107&authkey=!AHtA2TnLQUb5d9E&ithint=file%2cdb

1 个答案:

答案 0 :(得分:2)

我相信您可以通过加入Product,LineItem和Receipt来获得销售号码,然后计算收据ID:

SELECT P.id, P.flavor, P.kind, P.price, R.purchasedate, count(R.id) as numSold
FROM Product P join LineItem L on P.id = L.productID join Receipt R on L.receiptID = R.id 
GROUP BY R.purchasedate, P.id, P.flavor, P.kind, P.price
ORDER BY P.id, DATE(R.purchasedate);

要计算总数,您可以使用sum(P.price),但您可能需要加入Sale表以便计算折扣百分比。