日期:2014-05-17  浏览次数:20703 次

关于group by后的自动编号问题,求一句SQL语句
我要按日期统计一个表里数据,现有语句如下(dt是datetime的字段名)——
select convert(varchar(10),dt,120) as day2 from table1 group by convert(varchar(10),dt,120)
得到结果如下——
day2
2013-03-10
2013-03-09
2013-03-08
2013-03-07
我现在希望在结果的左边加一列id自动编号,如下——
id day2
4 2013-03-10
3 2013-03-09
2 2013-03-08
1 2013-03-07
这样的sql语句该怎么写?
我最终的目的是希望取得group by后的记录数,但是不知道应该怎么做,如果有了这个id数,我就能取到。
group?by?

------解决方案--------------------

select ID=ROW_NUMBER()OVER(ORDER BY day2 dt),convert(varchar(10),dt,120) as day2 from table1 group by convert(varchar(10),dt,120)
ORDER BY day2

------解决方案--------------------
select row_number() over(order by day2 desc) as id,day2
from (select convert(varchar(10),dt,120) as day2 from table1 group by convert(varchar(10),dt,120))T

------解决方案--------------------
select row_number()(order by convert(varchar(10),dt,120)
)as id,convert(varchar(10),dt,120) as day2 from table1 group by convert(varchar(10),dt,120)

------解决方案--------------------
----------------------------
-- Author  :TravyLee(两情若是久长时,又岂在朝朝暮暮!)
-- Date    :2013-03-11 14:58:54
-- Version:
--      Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (X64) 
-- Jul  9 2008 14:17:44 
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Developer Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:#test
if object_id('tempdb.dbo.#test') is not null drop table #test
go 
create table #test([day2] datetime)
insert #test
select '2013-03-10' union all
select '2013-03-09' union all
select '2013-03-08' union all
select '2013-03-07'
go
 
select (select count(1) from #test b where a.day2>=b.day2) AS ID,day2 from #test a
/*
ID day2
4 2013-03-10 00:00:00.000
3 2013-03-09 00:00:00.000
2 2013-03-08 00:00:00.000
1 2013-03-07 00:00:00.000
*/