读书人

从ASP.NET版块跑过来问的一个查询有关

发布时间: 2013-03-01 18:33:02 作者: rapoo

从ASP.NET版块跑过来问的一个查询问题。
从ASP.NET版块跑过来问的一个查询有关问题

数据如下:


SELECT HistoryId,Score,CONVERT(VARCHAR(10),Add_Datetime,23)as 'Add_Date'
from Table Group by Add_Datetime


HistoryId Score Add_Date
=====================================
1 12 2013-01-02
2 43 2013-01-02
3 50 2013-01-02
4 23 2013-01-02
5 89 2013-01-03
6 77 2013-01-03
7 63 2013-01-03
8 32 2013-01-04
9 90 2013-01-04
10 88 2013-01-04
=====================================

以上是模拟的,跟元素据也差不多了。。

需要得到的结果

HistoryId Score Add_Date
=====================================
3 50 2013-01-02
5 89 2013-01-03
9 90 2013-01-04
=====================================
GroupBy 每天 得到 Max(Score),Max(Score)的HistoryId也要得到。

反正结果要同时包含三列都有。

谢谢了。
sql GroupBy Select
[解决办法]
select * from tb t where score=
(select max(score) from tb where t.Add_Date=Add_Date group by Add_Date)
[解决办法]
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (HistoryId int,Score int,Add_Date datetime)
insert into [TB]
select 1,12,'2013-01-02' union all
select 2,43,'2013-01-02' union all
select 3,50,'2013-01-02' union all
select 4,23,'2013-01-02' union all
select 5,89,'2013-01-03' union all
select 6,77,'2013-01-03' union all
select 7,63,'2013-01-03' union all
select 8,32,'2013-01-04' union all
select 9,90,'2013-01-04' union all


select 10,88,'2013-01-04'

select * from [TB]

--方法1
SELECT *
FROM dbo.TB B
WHERE NOT EXISTS(SELECT 1 FROM TB A WHERE A.add_date = B.add_date AND A.score>B.score)



/*
HistoryIdScoreAdd_Date
3502013-01-02 00:00:00.000
5892013-01-03 00:00:00.000
9902013-01-04 00:00:00.000*/


[解决办法]
--方法2

SELECT historyid ,
score ,
add_date
FROM ( SELECT ROW_NUMBER() OVER ( PARTITION BY add_date ORDER BY score DESC ) AS NO ,
*
FROM dbo.TB
) A
WHERE no = 1

[解决办法]
关键你要还要查询出对应id,这个写法有很多,大同小异
要想提高效率关键看表中的索引是否合理

读书人网 >SQL Server

热点推荐