2016-05-01 73 views
1

目標:
如果您檢索任何重複的數據,即secondid列中的數據,則只能從最新日期檢索一行。例如,在下面的數據中,我有兩個不同的日期時間,我想從列secondid中的值6中檢索數據'2016-05-02 07:34:14.377'。僅顯示最新的行

問題:
我的代碼似乎沒有工作,我錯過了什麼。

信息:
有許多數據,你不能硬編碼代碼中的值。

CREATE TABLE [dbo].[testing2](
    [id] [int] NOT NULL, 
    [secondid] [int] NULL, 
    [value] [varchar](30) NULL, 
    [category] [int] NULL, 
    [test_id] [int] NULL, 
    [id_type] [int] NOT NULL, 
    [Testing2Datetime] [datetime] not NULL, 
CONSTRAINT [PK_testing2] PRIMARY KEY CLUSTERED 
(
    [id] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 


INSERT INTO [test].[dbo].[testing2] 
VALUES (3, 3, 'a' ,2 ,11 ,1, '2016-05-01 07:34:14.377'); 

INSERT INTO [test].[dbo].[testing2] 
VALUES (4, 4, 'a' ,2 ,11 ,1, '2016-05-01 07:34:14.377'); 

INSERT INTO [test].[dbo].[testing2] 
VALUES (5, 5, 'a' ,2 ,11 ,0, '2016-05-01 07:34:14.377'); 

INSERT INTO [test].[dbo].[testing2] 
VALUES (6, 6, 'a' ,2 ,11 ,2, '2016-05-01 07:34:14.377'); 

INSERT INTO [test].[dbo].[testing2] 
VALUES (7, 6, 'a' ,2 ,11 ,2, '2016-05-02 07:34:14.377'); 



select 
    bb.secondid, 
    max(bb.Testing2Datetime) 
from [dbo].[testing2] bb 
group by 
    bb.secondid, 
     bb.Testing2Datetime 

enter image description here

回答

2

Testing2Datetime最大值每柱本身就是Testing2Datetime。你應該從group by條款中刪除,而且只有secondid檢索最大值:

select 
    bb.secondid, 
    max(bb.Testing2Datetime) 
from [dbo].[testing2] bb 
group by 
    bb.secondid -- Here! 
+0

謝謝你的幫助! –

1

取下Group by

select 
    bb.secondid, 
    max(bb.Testing2Datetime) as [Max_Testing2Datetime] 
from [dbo].[testing2] bb 
group by 
    bb.secondid 

或者甚至這個(Row_Number窗函數)

select * 
from 
(
select 
    bb.secondid, 
    bb.Testing2Datetime, 
    Row_number()over(partition by bb.secondid order by bb.Testing2Datetime desc) as RN 
from [dbo].[testing2] bb 
) A 
Where RN = 1 
+0

謝謝您的幫助! –