目标:
如果您检索列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
答案 0 :(得分:2)
每Testing2Datetime
Testing2Datetime
的最大值是Testing2Datetime
本身。您应该从group by
子句中删除它,并仅按 secondid
检索最大值:
select
bb.secondid,
max(bb.Testing2Datetime)
from [dbo].[testing2] bb
group by
bb.secondid -- Here!
答案 1 :(得分:1)
从bb.Testing2Datetime
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