sql server 2012 - 按年,月,供应商和位置对订单进行排名

时间:2013-11-11 08:40:41

标签: sql sql-server max datepart

我有一张包含以下内容的表格。

pickup_date, Supplier_id, Location

pickup_date是日期时间,供应商ID是数字。位置是一个字符串。

我想输出一个使用下面两个datepart字段排序的列表(以匹配其他数据),为每个供应商提供每月结果。最后一列应显示每个供应商的最常见位置。

我相信我出错的地方是group_by的排序

datepart(year, b.pickup_date) Year,
datepart(month, b.pickup_date) Month,

我期待:年,月,Supplier_Id,“MostfrequentPickupLocation”。

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT 
  YEAR(pickup_date) AS 'PickupYear', 
  MONTH(pickup_date) AS 'PickupMonth', 
  Supplier_id,
  Location,
  COUNT(*)
FROM MyTable
GROUP BY   
  YEAR(pickup_date), 
  MONTH(pickup_date), 
  Supplier_id,
  Location

以下是我使用的SQL小提琴:http://sqlfiddle.com/#!6/d9751/6

答案 1 :(得分:0)

如果您只想为每个供应商显示一条记录:

WITH cte AS
(
  SELECT 
    YEAR(pickup_date) AS 'Year', 
    MONTH(pickup_date) AS 'Month', 
    Supplier_id,
    Location,
    COUNT(*) as NoAppeareances,
    ROW_NUMBER() OVER (PARTITION BY Supplier_id ORDER BY COUNT(*) DESC) RowNumber 
FROM MyTable
GROUP BY   
  YEAR(pickup_date), 
  MONTH(pickup_date), 
  Supplier_id,
  Location
)
SELECT Year, Month, Supplier_id, NoAppeareances as MostfrequentPickupLocation
FROM cte
WHERE RowNumber = 1