Sql Query基于最大数量的唯一记录

时间:2013-06-14 17:24:18

标签: c# asp.net gridview sql-server-2008-r2

我有一个当前显示的gridview,如右上图所示。我希望它只显示具有最长时间的记录,如图2所示。例如,对于Q1最大时间是15分钟,所以只显示Q1 15分钟等。这是动态的,因此字母和数字可能会改变。有人知道一个好的SQL服务器查询吗?

已更新

enter image description here

2 个答案:

答案 0 :(得分:2)

这对你有用吗?

Select distinct Number, MAX(Time) from MyTable group by Number

评论后

create table #example(number varchar(50), id int, [time] nvarchar(50), descr nvarchar(50))
insert into #example (number, id, [time], descr) values ('Q1', 1, '10 Min', 'Shoe')
insert into #example (number, id, [time], descr) values ('Q1', 1, '15 Min', 'Car')
insert into #example (number, id, [time], descr) values  ('Q1', 1, '6 Min', 'Shirt')
insert into #example (number, id, [time], descr) values  ('L2', 1, '10 Min', 'Shoe')
insert into #example (number, id, [time], descr) values  ('P3', 2, ' 8 Min', 'Garage')
insert into #example (number, id, [time], descr) values  ('P3', 2, ' 3 Min', 'Plant')
insert into #example (number, id, [time], descr) values  ('P3', 2, '20 Min', 'Tree')

SELECT t1.*
FROM #example AS t1
LEFT OUTER JOIN #example AS t2
    ON (t1.number = t2.number AND t1.[time] < t2.[time])
WHERE t2.number IS NULL;
--In other words: fetch the row from t1 where no other row exists with the same Number and a greater Time.

答案 1 :(得分:0)

我不确定这是否是您要找的,但请查看:

create table #test (name varchar(10), number int)
insert into #test values ('a', 1)
insert into #test values ('a', 2)
insert into #test values ('a', 3)
insert into #test values ('b', 1)
insert into #test values ('b', 2)
insert into #test values ('b', 4)

select name, max(number) from #test group by name

结果:

name    (No column name)
a   3
b   4