我有一张包含以下内容的表格。
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”。
答案 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