日期:2014-05-17 浏览次数:20581 次
select
a.id,
a.date,
a.no_head,
a.no_state
from test a
left join (
select distinct
max (date) as date,
--max(no_state) as no_state,
--max(id) as id,
no_head
from test
group by no_head --,no_state
) b on a.no_head = b.no_head
where a.date = b.date
-- ----------------------------
-- Table structure for [dbo].[test]
-- ----------------------------
DROP TABLE [dbo].[test]
GO
CREATE TABLE [dbo].[test] (
[id] int NOT NULL ,
[date] datetime NULL ,
[no_head] varchar(2) NULL ,
[no_state] varchar(2) NULL
)
GO
-- ----------------------------
-- Records of test
-- ----------------------------
INSERT INTO [dbo].[test] ([id], [date], [no_head], [no_state]) VALUES (N'1', N'2013-11-16 00:00:00.000', N'01', N'a');
GO
INSERT INTO [dbo].[test] ([id], [date], [no_head], [no_state]) VALUES (N'2', N'2013-11-17 00:00:00.000', N'01', N'b');
GO
INSERT INTO [dbo].[test] ([id], [date], [no_head], [no_state]) VALUES (N'3', N'2013-11-18 00:00:00.000', N'01', N'c');
GO
INSERT INTO [dbo].[test] ([id], [date], [no_head], [no_state]) VALUES (N'4', N'2013-11-17 00:00:00.000', N'02', N'a');
GO
INSERT INTO [dbo].[test] ([id], [date], [no_head], [no_state]) VALUES (N'5', N'2013-11-16 00:00:00.000', N'02', N'b');
GO
-- ----------------------------
-- Indexes structure for table test
-- ----------------------------
-- ----------------------------
-- Primary Key structure for table [dbo].[test]
-- ----------------------------
ALTER TABLE [dbo].[test] ADD PRIMARY KEY ([id])
GO