SQL按日期和月份排序日期

时间:2016-05-01 01:05:30

标签: sql pgadmin

this.chart.height

Please look at the picture

我想按年份和月份查询OrderDate组,因此可以将同月的数据添加到一起

非常感谢你的帮助

3 个答案:

答案 0 :(得分:1)

您需要从日期中提取年份和月份,并使用selectgroup 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上)