22,209
社区成员
发帖
与我相关
我的任务
分享
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2009-09-01 23:03:16
-- Verstion:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([file] varchar(1),[ID] int)
insert [tb]
select 'a',1 union all
select 'b',1 union all
select 'c',2
--------------开始查询--------------------------
select id,max([file]) as testfile from tb group by id
select id,[file] from tb t where not exists(select 1 from tb where id=t.id and [file]>t.[file])
----------------结果----------------------------
/*id testfile
----------- --------
1 b
2 c
(2 行受影响)
*/
create table #a([file] VARCHAR(10),[ID] INT)
insert #a select 'a',1 union all
select 'b',1 union all
select 'c',2
select * from #a
DECLARE @s VARCHAR(8000)
SELECT @s = 'SELECT [ID]'
SELECT @s = @s + ',MAX(CASE WHEN sequence = ''' + RTRIM(sequence) + ''' THEN [file] END) AS ' + 'file' + RTRIM(sequence)
FROM (SELECT DISTINCT sequence FROM (SELECT *,ROW_NUMBER()OVER(PARTITION BY [ID] ORDER BY GETDATE()) AS sequence FROM #a)X)Y
SELECT @s = @s + ' FROM (SELECT *,ROW_NUMBER()OVER(PARTITION BY [ID] ORDER BY GETDATE()) AS sequence FROM #a)X GROUP BY [ID]'
EXEC (@s)
select * from tb t where not exists(select 1 from tb where id=t.id and file>t.file)
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2009-09-01 23:03:16
-- Verstion:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([file] varchar(1),[ID] int)
insert [tb]
select 'a',1 union all
select 'b',1 union all
select 'c',2
--------------开始查询--------------------------
select id,max([file]) as testfile from tb group by id
----------------结果----------------------------
/*id testfile
----------- --------
1 b
2 c
(2 行受影响)
*/