我正在使用的两个表
Orderdetails
ordernumber, productnumber, productcode, quantityordered, priceEach
Orders
ordernumber, orderdate (labeled as yyyy-mm-dd)
我了解获得收入Sum( quantityOrdered * priceEach ) as TotalRevenue
。
难以按月分组并连接两个表。
谢谢
答案 0 :(得分:0)
在标准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;
答案 1 :(得分:0)
我将使用T-SQL。将T-SQL转换为其他SQL方言很简单。
首先,通过将所有OrderDetails
按OrderNumber
和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
然后,我们要按行(月和月的元组)对行进行分组,并在每个组中找到SUM
中的OrderValue
。我们可以不再使用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
答案 2 :(得分:0)
您可以将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;