假设我有一个名为的表'@DeviceSample'
和另一个名为'@DevicesActivityDataSample'.
'MAX(DATETIME)'
当我在“ DevicesActivityDataSample ”中有重复的行时,我想为每个设备选择前 1 个'@DevicesActivityDataSample'
,但在我的结果中,我得到了所有重复的行,但我在寻找前一个。另一个问题是,当我想从 100000 行中选择时,由于计算 MAX,需要很长时间才能得到我的结果,这是我的示例代码
DECLARE @DeviceSample TABLE
(
RowID INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
ADeviceID INT ,
DeviceName VARCHAR(50) NOT NULL
)
INSERT @DeviceSample
SELECT 1,'DEVICE 1' UNION ALL
SELECT 2,'DEVICE 2' UNION ALL
SELECT 3,'DEVICE 3'
DECLARE @DevicesActivityDataSample TABLE
(
RowID INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
BDeviceID INT,
DeviceDateTime DATETIME,
CMD NVARCHAR(50)
)
INSERT @DevicesActivityDataSample
SELECT 1, '2013-02-14 19:08:46.000','HHJJ' UNION ALL
SELECT 2, '2013-02-15 03:30:24.000','HHJJ' UNION ALL
SELECT 2, '2013-02-15 03:30:24.000','HHJJ' UNION ALL
SELECT 2, '2013-02-15 03:30:24.000','HHJJ' UNION ALL
SELECT 1, '2013-02-16 03:30:24.000','HHJJ' UNION ALL
SELECT 1, '2013-02-11 03:30:24.000','HHJJ' UNION ALL
SELECT 2, '2013-02-10 03:30:24.000','HHJJ' UNION ALL
SELECT 3, '2013-02-07 04:25:24.000','HHJJ' UNION ALL
SELECT 3, '2013-02-12 23:02:02.000','HHJJ'
SELECT *
FROM @DeviceSample
INNER JOIN
@DevicesActivityDataSample
ON ADeviceID = BDeviceID
WHERE DeviceDateTime IN (
SELECT MAX(DeviceDateTime) AS MaxDate
FROM @DevicesActivityDataSample
GROUP BY BDeviceID
)
GO
以及如何获得 1000000 行或更多行的快速快速结果