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;
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;
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;
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
然后我们要按行的月份(一个年和月的元组)对行进行分组,并找到 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
3条答案
按热度按时间im9ewurl1#
您可以使用分组方式
month
以及year
共同起作用rextester演示
hjqgdpho2#
在标准sql中,您将执行以下操作:
众所周知,数据库对日期/时间函数的支持是多种多样的。许多人支持更简单的方法
year()
以及month()
功能。许多人支持其他机制来做同样的事情。在mysql中,可以使用
year()
以及month()
功能:5hcedyr03#
我将使用t-sql。将t-sql转换为其他sql方言很简单。
首先,我们将所有订单分组,得到每个订单的总收入
OrderDetails
由OrderNumber
以及SUM
降低其价值:这给了我们这个输出:
那么
JOIN
这个和Orders
为了得到他们的OrderDate
:这给了我们这个输出:
然后我们要按行的月份(一个年和月的元组)对行进行分组,并找到
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