答案 0 :(得分:1)
您需要从日期中提取年份和月份,并使用select
和group by
列中的年份和月份。如何执行此操作在很大程度上取决于数据库。许多支持称为year()
和month()
的函数。
然后你需要按你想要的字段聚合。像这样:
SELECT YEAR(so.OrderDate) as yyyy, MONTH(so.OrderDate) as mm,
b.BookID, b.title,
COUNT(so.ShopOrderID) AS "Total number of order",
SUM(ol.Quantity) AS "Total quantity",
SUM(ol.UnitSellingPrice * ol.Quantity AS "Total order value",
SUM(b.Price * ol.Quantity) AS "Total retail value"
FROM ShopOrder so JOIN
Orderline ol
ON ol.ShopOrderID = so.ShopOrderID JOIN
Book b
ON b.BookID = ol.BookID JOIN
Publisher p
ON p.PublisherID = b.PublisherID
WHERE p.name = 'Addison Wesley'
GROUP BY YEAR(so.OrderDate), MONTH(so.OrderDate), b.BookID, b.title
ORDER BY MIN(so.OrderDate)
请注意,使用表别名可以使查询更容易编写和读取。
以上在MySQL,DB2和SQL Server中有效。在Postgres和Oracle中,to_char(so.OrderDate, 'YYYY-MM')
。
答案 1 :(得分:0)
对于组,您可以使用datepart函数
GROUP BY (DATEPART(yyyy, ShopOrder.OrderDate), DATEPART(mm, ShopOrder.OrderDate))
答案 2 :(得分:0)
你应该聚合
, Orderline.UnitSellingPrice * Orderline.Quantity AS "Total order value"
, book.Price * Orderline.Quantity AS "Total retail value"
或者您将count(...)
个值等于1。
YEAR(myDate)
的{{1}}和MONTH(myDate)
是group by
函数的便捷快捷方式(在MS SQL Server上)