首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求sql 话语?

2013-03-21 
求sql 语句???原来的表 col1col2col3aa52013-02-15 14:47:11aa72013-02-16 15:12:23aa62013-02-17 16:21:5

求sql 语句???
原来的表

 col1     col2        col3
  aa       5      2013-02-15 14:47:11
  aa       7      2013-02-16 15:12:23
  aa       6      2013-02-17 16:21:55
  bb       9      2013-02-15 14:47:11
  bb       7      2013-02-16 15:12:23
  bb       6      2013-02-19 16:21:42
  bb       3      2013-02-15 14:47:11
  cc       1      2013-02-17 15:12:23
  cc       8      2013-02-17 16:21:57
  dd       6      2013-02-18 09:21:23

需要得到表中记录  获取的条件就是  col3中 时间最大的记录。
 col1     col2        col3
  aa       6      2013-02-17 16:21:55
  bb       6      2013-02-19 16:21:42
  cc       8      2013-02-17 16:21:57
  dd       6      2013-02-18 09:21:23



[解决办法]
select * from 表 a where not exists (select 1 from 表 where col1=a.col1 and a.col3<col3) 
[解决办法]
select * from tb a where exists 
(select 1 from tb where col1=a.col1 group by col1 having max(col3)=a.col3)  
[解决办法]

select * from 表 as a  where not exists(select * from 表 where col1=a.col1 and col3>a.col3 )

[解决办法]
----------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2013-02-18 16:29:34
-- Version:
--      Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64) 
--Jun 17 2011 00:54:03 
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([col1] varchar(2),[col2] int,[col3] datetime)


insert [huang]
select 'aa',5,'2013-02-15 14:47:11' union all
select 'aa',7,'2013-02-16 15:12:23' union all
select 'aa',6,'2013-02-17 16:21:55' union all
select 'bb',9,'2013-02-15 14:47:11' union all
select 'bb',7,'2013-02-16 15:12:23' union all
select 'bb',6,'2013-02-19 16:21:42' union all
select 'bb',3,'2013-02-15 14:47:11' union all
select 'cc',1,'2013-02-17 15:12:23' union all
select 'cc',8,'2013-02-17 16:21:57' union all
select 'dd',6,'2013-02-18 09:21:23'
--------------开始查询--------------------------

SELECT  *
FROM    [huang] AS a
WHERE   EXISTS ( SELECT 1
                 FROM   ( SELECT    col1 ,
                                    MAX(col3) col3
                          FROM      huang
                          GROUP BY  col1
                        ) b
                 WHERE  a.col1 = b.col1
                        AND A.col3 = b.col3 )
----------------结果----------------------------
/* 
col1 col2        col3
---- ----------- -----------------------
aa   6           2013-02-17 16:21:55.000
bb   6           2013-02-19 16:21:42.000
cc   8           2013-02-17 16:21:57.000
dd   6           2013-02-18 09:21:23.000

(4 行受影响)
*/

热点排行