根据sql产生的收入量对月份进行排名

a2mppw5e  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(280)

我工作的两张table是

Orderdetails
ordernumber, productnumber, productcode, quantityordered, priceEach

Orders
ordernumber, orderdate (labeled as yyyy-mm-dd)

我理解你的收入 Sum( quantityOrdered * priceEach ) as TotalRevenue .
难以按月份分组并将两个表连接起来。
谢谢您

im9ewurl

im9ewurl1#

您可以使用分组方式 month 以及 year 共同起作用

select concat(month(orderdate),'/',year(orderdate)) as term,
       Sum( quantityOrdered * priceEach ) as TotalRevenue
  from Orders o
  left join Orderdetails d on o.ordernumber = d.ordernumber
 group by term;

rextester演示

hjqgdpho

hjqgdpho2#

在标准sql中,您将执行以下操作:

select extract(year from o.orderdate) as yyyy,
       extract(month from o.orderdate) as mm,
       sum(ol.quantityOrdered * ol.priceEach) as total
from orders o join
     orderlines ol
     on o.ordernumber = ol.ordernumber
group by extract(year from o.orderdate), extract(month from o.orderdate)
order by yyyy, mm;

众所周知,数据库对日期/时间函数的支持是多种多样的。许多人支持更简单的方法 year() 以及 month() 功能。许多人支持其他机制来做同样的事情。
在mysql中,可以使用 year() 以及 month() 功能:

select year(o.orderdate) as yyyy,
       month(o.orderdate) as mm,
       sum(ol.quantityOrdered * ol.priceEach) as total
from orders o join
     orderlines ol
     on o.ordernumber = ol.ordernumber
group by year(o.orderdate), 
order by yyyy, mm;
5hcedyr0

5hcedyr03#

我将使用t-sql。将t-sql转换为其他sql方言很简单。
首先,我们将所有订单分组,得到每个订单的总收入 OrderDetailsOrderNumber 以及 SUM 降低其价值:

SELECT
    OrderNumber,
    SUM( QuantityOrdered * PriceEach ) AS OrderValue
FROM
    OrderDetails
GROUP BY
    OrderNumber

这给了我们这个输出:

OrderNumber    OrderValue
          1        123.00
          2        456.00   
          3         50.00
          4       1024.00

那么 JOIN 这个和 Orders 为了得到他们的 OrderDate :

SELECT
    Orders.OrderNumber,
    Orders.OrderDate,
    COALESCE( ov.OrderValue, 0 ) AS OrderValue
FROM
    OrderDetails
    LEFT OUTER JOIN
    (
        SELECT
            OrderNumber,
            SUM( QuantityOrdered * PriceEach ) AS OrderValue
        FROM
            OrderDetails
        GROUP BY
           OrderNumber
    ) AS ov ON ov.OrderNumber = Orders.OrderNumber

这给了我们这个输出:

OrderNumber   OrderDate  OrderValue
          1   2018-02-03     123.00
          2   2018-05-09     456.00   
          3   2018-02-04      50.00   
          4   2018-06-08    1024.00

然后我们要按行的月份(一个年和月的元组)对行进行分组,并找到 SUMOrderValue 在每组内。我们可以抛弃 OrderNumber 列,因为它不再需要。我们还可以添加 COUNT 我也是。那么 ORDER BY 这个 SUM ```
SELECT
YEAR( Orders.OrderDate ) AS [Year],
MONTH( Orders.OrderDate ) AS [Month],
COUNT( * ) AS [OrderCount],
SUM( COALESCE( ov.OrderValue, 0 ) ) AS RevenueInMonth
FROM
OrderDetails
LEFT OUTER JOIN
(
SELECT
OrderNumber,
SUM( QuantityOrdered * PriceEach ) AS OrderValue
FROM
OrderDetails
GROUP BY
OrderNumber
) AS ov ON ov.OrderNumber = Orders.OrderNumber
GROUP BY
YEAR( Orders.OrderDate ),
MONTH( Orders.OrderDate )
ORDER BY
RevenueInMonth DESC

这给了我们这个输出:

Year Month OrderCount RevenueInMonth
2018 6 1 1024.00
2018 5 1 456.00
2018 2 2 173.00

相关问题