【问题标题】:SQL to count turnover and group by month (please check)SQL按月统计营业额和分组(请检查)
【发布时间】:2018-04-27 22:34:45
【问题描述】:

我有三张桌子,我需要计算 John Smith 在 2015 年的营业额除以月数。

                   OrderItems
                   ------------       Orders
Products           OrderItem_ID       ------
----------         Order_ID   <--->   Order_ID
Product_ID  <--->  Product_ID         Type
Name               Quantity           Date
Category           UnitPrice          Customer

这些表通过 Order_ID 和 Order_ID(选项卡 OrderItems 和 Orders)和 Product_IDs(选项卡 Products 和 OrderItems)连接。我想我无论如何都不需要标签产品。

Orders (Order_ID INT, Type INT, Date DATETIME, Customer VARCHAR)
OrderItems (OrderItem_ID INT, Order_ID INT, Product_ID INT, Quantity INT, UnitPrice MONEY)
Products (Product_ID INT, Name VARCHAR, Category VARCHAR)

我已经用了几十分钟的谷歌搜索和知识更新,因为我已经很久没有使用 SQL 了。

我写了这个查询,但我完全不确定。请检查一下好吗?

SELECT
    SUM(a.quantity * a.price) AS 'turnover',
    DATEPART(month, a.date) AS 'month'
FROM 
(
    SELECT  
        Quantity.OrderItems AS 'quantity',
        UnitPrice.OrderItems AS 'price',
        Date.Orders AS 'date',
        Customer.Orders AS 'customer'
    FROM Orders
    JOIN Orders 
        ON OrderItems.Order_ID = Orders.Order_ID
    WHERE
        date BETWEEN 2015-01-01 and 2015-12-31
        AND customer = 'John Smith'
) a
GROUP BY month
ORDER BY month

非常感谢

//更正了代码中的一个小错字

【问题讨论】:

  • 您使用的是哪个DBMS 产品? “SQL”只是一种查询语言,并不是特定数据库产品的名称。
  • 尝试运行你的内部查询——它不应该编译。您需要将orders 加入orderitems,而不是再次加入orders
  • 另外,您的 group by 无法引用您的别名 month。你需要group by 你的datepart 函数。如果您在内部查询中返回您的月份datepart,可能会更容易理解。
  • 不幸的是我无法编译它。它是通用 SQL 中的离线练习 :-( 看起来很容易但是......所以我将加入这样的表 JOIN OrdersItems ON Orders.Order_ID = OrderItems.Order_ID 并按 DATEPART(month, a.date) 分组

标签: sql group-by calc


【解决方案1】:

你需要加入OrdersOrderItems

SELECT
    SUM(a.quantity * a.price) AS 'turnover',
    DATEPART(month, a.date) AS 'month'
FROM 
(
    SELECT  
        OI.Quantity AS 'quantity',
        OI.UnitPrice AS 'price',
        O.Date AS 'date',
        O.Customer AS 'customer'
    FROM Orders O
    INNER JOIN OrderItems OI
        ON O.Order_ID = OI.Order_ID
    WHERE
        O.date BETWEEN 2015-01-01 and 2015-12-31
        AND O.customer = 'John Smith'
) a
GROUP BY DATEPART(month, a.date)
ORDER BY DATEPART(month, a.date)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多