0

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

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”。

4

2 回答 2

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 Fiddle:http ://sqlfiddle.com/#!6/d9751/6

于 2013-11-11T08:56:44.273 回答
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
于 2013-11-11T09:16:15.940 回答