我的表具有以下简单架构:
Name | WorkingOn | Blockers | Completed | Date
---------------------------------------------------
Andy | Stuff | Test | test | 2018-08-08 14:37:10.460
Andy | Dummy | Test | test | 2018-08-09 14:37:10.460
Paul | Dummy | Test | test | 2018-08-10 14:37:10.460
除“日期”为varchar
值外,每个列均为datetime
。
我想做的是按最新的日期对结果进行排序,并按Name
分组所有内容
我认为可以使用以下SQL代码完成此操作:
SELECT mt.Name, mt.WorkingOn, my.Blockers, mt.Completed, mt.Date
FROM dbo.MyTable mt
GROUP BY mt.Name
ORDER BY my.date DESC
运行此命令时,出现以下错误:
Column 'dbo.MyTable .WorkingOn' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
我需要更改什么才能使结果返回我想要的结果?
答案 0 :(得分:1)
我想您希望按日期显示最后一行,请尝试以下操作:
select * from (
select Name, WorkingOn, Blockers, Completed, Date,
row_number() over(partition by Name order by Date desc) rang
from yourtable
) tmp where tmp.rang=1
答案 1 :(得分:1)
您的描述描述了聚合和排序。似乎可以描述此查询:
SELECT mt.Name, mt.WorkingOn, my.Blockers, mt.Completed, MAX(mt.Date)
FROM dbo.MyTable mt
GROUP BY mt.Name, mt.WorkingOn, my.Blockers, mt.Completed
ORDER BY MAX(my.date) DESC
这将按名称*和其他列汇总列,以提取最大日期。
我认为那不是你想要的。如果您只想对行进行排序,那么可能就是您想要的:
select mt.*
from dbo.mytable mt
order by max(mt.date) over (partition by name), name, mt.date desc;
这将按每个名称的最大日期对原始行进行排序。它保留所有行,但是将名称的行分组在一起。
或者,也许聚合与您的问题无关:
select top (1) with ties mt.*
from dbo.mytable mt
order by row_number() over (partition by name order by mt.date desc);
这将保留每个名称的最新日期。
答案 2 :(得分:0)
SELECT mt.Name, mt.WorkingOn, my.Blockers, mt.Completed, mt.Date
FROM dbo.MyTable mt
GROUP BY mt.Name, mt.Date, mt.WorkingOn, my.Blockers, mt.Completed,
ORDER BY my.Date DESC
它应该可以解决问题,因为在这种情况下,您需要将所有列都放在Group by子句中。
答案 3 :(得分:0)
根据您的要求-
SELECT mt.Name, mt.WorkingOn, my.Blockers, mt.Completed, mt.Date
FROM dbo.MyTable mt
GROUP BY mt.Name, mt.WorkingOn, my.Blockers, mt.Completed, mt.Date
ORDER BY my.date DESC
请click here在SQL Server中按规则分组